虽然JQ里自带了fadeOut和fadeIn动画特效,但在实际使用中它们远远不及CSS3动画那样流畅顺滑。如果忽略所差的那一点兼容性,CSS3动画必然是更好的选择。代码中JQ的作用其实只是给元素添加/删除class,换成js也是一样的。
Html结构
<ul class="father"><!-- 父级块元素 -->
<li class="children">'内容和图片'</li>
<li class="children">'内容和图片'</li>
<li class="children">'内容和图片'</li>
<!-- N个子元素 -->
</ul>
CSS样式及定义动画
<style type="text/css">
/* reset */
* {
margin:0;
padding:0;
}
img {
border:0;
}
ul {
list-style-type:none
}
/* CSS 动画 */
@keyframes show{
from{opacity:0}
to{opacity:1}
}
@-webkit-keyframes show{
from{opacity:0}
to{opacity:1}
}
@keyframes hide{
from{opacity:1}
to{opacity:0}
}
@-webkit-keyframes hide{
from{opacity:1}
to{opacity:0}
}
/* 播放动画的类 */
/* 这个相当于fadeIn */
.animate-show-slow {
animation:show 3s linear;
-webkit-animation:show 3s linear;
animation-fill-mode:forwards;
-webkit-animation-fill-mode:forwards;
-moz-animation-fill-mode:forwards;
}
/* 这个相当于fadeOut */
.animate-hide-slow {
animation:hide 3s linear;
-webkit-animation:hide 3s linear;
animation-fill-mode:forwards;
-webkit-animation-fill-mode:forwards;
-moz-animation-fill-mode:forwards;
}
/* 元素样式 */
/*
* 父容器主要作用是限制子元素的位置和在页面中定位
* position:relative 作用是让子元素absolute的时候相对于父元素定位,不会跑偏
* 背景设为黑色可以让图片淡入淡出时有变暗效果
*/
.father {
width:800px;
height:600px;
background:#000;
position:relative;
margin:0 auto;
}
/*
* 子元素采用了设置背景图的方式,而不是直接放入<img>标签,为的是方便内容排版
* 而且背景图设置了cover属性,是纯天然的响应式效果
* 当然在内容中图文混排也是个好选择
*/
.children {
width:100%;
height:100%;
background-size:cover;
background:url(图片地址) no-repeat center fixed;
position:absolute;
top:0;
left:0
}
/*
* 如果想让图片显示的柔和些,可以在.children中再加一级子元素,比如叫做.cover
* 设置透明背景,相当于给图片加了一个滤镜
* 然后再在.cover中做内容排版
*/
.cover {
width:100%;
height:100%;
background:rgba(0,0,0,0.6);
}
</style>
jQuery代码
/* 引入百度JQ库 */
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
/*
* 轮播方法
* @param {slider} JQ对象
* @param {interval} 图片停留的时间 (ms)
* 淡入淡出速度已在CSS中定义
*/
function carouselPic(slider, interval){
var i = 0;
slider.eq(0).addClass("animate-show-slow")
.siblings().addClass("animate-hide-slow");
setInterval(function() {
(slider.length > i + 1) ? i++ : i = 0;
slider.eq(i)
.addClass("animate-show-slow")
.removeClass("animate-hide-slow")
.siblings()
.addClass("animate-hide-slow")
.removeClass("animate-show-slow");
}, interval);
}
/* 调用 */
$(function(){
carouselPic( $(".father .children"), 6000 ); // 每6秒切换一次,时间可根据需要调整
});
</script>