这是一款非常简单的带前后控制按钮的jQuery和CSS3 3D旋转木马特效。该旋转木马特效使用CSS3 3D transforms属性来渲染一个3D立体旋转木马,并通过简单的jQuery代码来控制旋转木马的旋转动画。
关于3D旋转木马的制作教程,可以参看:CSS3 3D transforms系列教程-3D旋转木马。
使用方法
HTML结构
该3D旋转木马的HTML结构如下,其中<nav>元素是前后导航按钮。
<div id="carousel">
<div id="container" tcc-rotation="0">
<item><img src="img/1.jpg"></item>
<item><img src="img/2.jpg"></item>
<item><img src="img/3.jpg"></item>
<item><img src="img/4.jpg"></item>
<item><img src="img/5.jpg"></item>
<item><img src="img/6.jpg"></item>
</div>
<nav class="tc-btn-container">
<div class="tc-next">NEXT</div>
<div class="tc-prev">PREV</div>
</nav>
</div>
CSS样式
需要为该3D旋转木马特效添加以下的一些CSS样式。由于IE浏览器不支持transform-style: preserve-3d;属性,所以在IE浏览器中是看不到3D透视效果的。
#carousel {
display: block;
height: auto;
margin: 0 auto;
-webkit-perspective: 80px;
perspective: 800px;
position: relative;
top: 200px;
width: 800px;
}
#container {
display: block;
height: 200px;
margin: 0 auto;
transform: rotateY(0deg);
-webkit-transform-origin: center bottom 0;
transform-origin: center bottom 0;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
width: 200px;
}
item {
display: block;
margin: 0;
padding: 0;
width: 200px;
transform: translateZ(400px);
position: absolute;
}
item img { width: 100%; }
.tc-btn-container {
display: block;
float: left;
height: 35px;
margin-top: -12.5px;
position: absolute;
top: 50%;
width: 100%;
}
.tc-next {
background-color: #333;
color: white;
display: block;
float: right;
font-size: 12px;
padding: 10px;
width: auto;
cursor: pointer;
}
.tc-prev {
background-color: #333;
color: white;
display: block;
float: left;
font-size: 12px;
padding: 10px;
width: auto;
cursor: pointer;
}
JavaScript
在页面初始化完毕之后,可以通过下面的代码来激活该3D旋转木马插件。
$(document).ready(function($){
var crotation;
var rotateto = 0;
var halfrotation = 180;
function tcRotate(deg){
$('#container').css({
'transform' : 'rotateY('+ deg +'deg)',
'-webkit-transform' : 'rotateY('+ deg +'deg)'
});
}
$('item').on('click', function(e){
e.preventDefault();
crotation = $('#container').attr('tcc-rotation');
rotation = $(this).attr('tc-rotation');
rotateto = crotation - rotation;
tcRotate(rotateto);
crotation = rotateto;
});
$('.tc-next').on('click', function(e){
e.preventDefault();
rotateto -= 60;
tcRotate(rotateto);
});
$('.tc-prev').on('click', function(e){
e.preventDefault();
rotateto += 60;
tcRotate(rotateto);
});
});
该旋转木马插件的github地址为:https://github.com/marffinn/jQuery-CSS-Carousel