一、效果抢先
您可以狠狠地点击这里:纯CSS下的图片轮转播放效果demo
如果您手头上的浏览器是FireFox6+,或者教新版本的Chrome或是Safari浏览器,就可以看到类似上面截图的效果。完全CSS挑大梁,JS请假回家相亲去了。
二、原理简述
显然,要实现demo所示的效果,CSS2.1就算是天天蹲在茅坑上,也拉不出一坨冰激凌形状的屎,必须使用CSS3,因此,demo页面的效果只能跟元老级的IE浏览器说“搞咩纳塞”了。
这里应用的CSS3属性是animate动画。关于CSS3 的animate属性,可以参考“CSS3 Transitions, Transforms和Animation使用简介与应用展示”一文,其中有非常详尽的讲解。
本文之所以又拿CSS3动画说事,是为了补充CSS3 animate属性下的新出来的个关键字属性step。之前我们应用animate动画,出现的效果都是很平滑很流畅的。而step的作用是分步实现。好像舞蹈中优美流畅的华尔兹和动感的机械舞。
例如下面文字打印,光标闪闪的效果:
我知道的使用有两个,一个是step-end,即一次性动画结束,另外一个就类似于steps(30, end),一个动画要顿30次完成。本文的图片滚动demo部分右下角的序号就使用了step-end。
上下滚动的实现很简单,设置对应的时间段(百分比)和对应的列表的垂直位置即可。以FireFox浏览器举例(下同),相关代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@-moz-keyframes slide { from, to { top: 0; } 12.5% { top: 0; } 25% { top: -375px; } 37.5% { top: -375px; } 50% { top: -750px; } 62.5% { top: -750px; } 75% { top: -1125px; } 87.5% { top: -1125px; } } .list{ -moz-animation: slide 20s infinite; } |
右下角的图片码数的切换使用了animate属性的step-end,相关CSS如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
@-moz-keyframes index_1 { from, 25%, to { background-color: rgba(0,0,0,.5); } 0% { background-color: rgba(255,0,0,.5); } } @-moz-keyframes index_2 { from, 50%, to { background-color: rgba(0,0,0,.5); } 25% { background-color: rgba(255,0,0,.5); } } @-moz-keyframes index_3 { from, 75%, to { background-color: rgba(0,0,0,.5); } 50% { background-color: rgba(255,0,0,.5); } } @-moz-keyframes index_4 { from, 100%, to { background-color: rgba(0,0,0,.5); } 75% { background-color: rgba(255,0,0,.5); } } .index_1{ -moz-animation: index_1 20s step-end infinite; } .index_2{ -moz-animation: index_2 20s step-end infinite; } .index_3{ -moz-animation: index_3 20s step-end infinite; } .index_4{ -moz-animation: index_4 20s step-end infinite; } |
然后相对应的完整HTML代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<div class="box"> <ul class="list"> <li><img class="slide" src="http://image.zhangxinxu.com/image/study/p/s500/ps1.jpg" height="375" /></li> <li><img class="slide" src="http://image.zhangxinxu.com/image/study/p/s500/ps2.jpg" height="375" /></li> <li><img class="slide" src="http://image.zhangxinxu.com/image/study/p/s500/ps3.jpg" height="375" /></li> <li><img class="slide" src="http://image.zhangxinxu.com/image/study/p/s500/ps4.jpg" height="375" /></li> </ul> <div class="index"> <a href="javascript:" class="index_1">1</a> <a href="javascript:" class="index_2">2</a> <a href="javascript:" class="index_3">3</a> <a href="javascript:" class="index_4">4</a> </div> </div> |
说穿了很简单的,你要是有兴趣,可以去查看demo页面处的代码展示,那里更加详尽。
三、结语
本处的demo更多的是展示CSS3 animate的使用,想要在实际项目中使用还是有些问题的。例如鼠标移到相对应的序号索引小按钮上,应该会有对应的即时响应滚动效果的,现在没有。这里只是个没有交互,纯粹的展示效果而已。
虽然说本文的demo效果尚不可实际应用,但对于熟悉和了解CSS3的一些属性还是很有帮助的。我们可以使用渐进增强,在其他地方应用CSS3优秀的特性。这可以让你的网页进一步蓬荜生辉的。