CSS实现轮播图广告效果
对于用 css 实现一个轮播图的缘由,是那时候刚开始接触前端,完全还不懂 js。但是有一个项目(就是一个用来应付面试的作品)需要做一个轮播的效果,当时第一反应就是用 css3 自定义动画 -webkit-animation。做出来的效果自己觉得还可以,唯一的不足就是鼠标点击切换 banner 图和指定到某个图。如果项目中不需要切换变换图片的需求,用 css3 做,何尝不是一种办法。不多说,先上代码:
html 代码如下:
<div class="test">
<a href="#" ><img class="img1" src="1.jpg" ></a>
<a href="#" ><img class='img2' src="2.jpg" ></a>
<a href="#" ><img class='img3' src="3.jpg" ></a>
<a href="#" ><img class='img4' src="4.jpg" ></a>
</div>
接着 css 代码:
@-webkit-keyframes t1{
0%{ left: 0; }
20%{ left: 0; }
25%{ left: -960px; }
45%{ left: -960px; }
50%{ left: -1920px; }
70%{ left: -1920px; }
75%{ left: -2880px; }
95%{ left: -2880px; }
100%{ left: 0; }
}
@-webkit-keyframes t2{
0%{ left: 960px; }
20%{ left: 960px; }
25%{ left: 0; }
45%{ left: 0; }
50%{ left: -960px; }
70%{ left: -960px; }
75%{ left: -1920px; }
95%{ left: -1920px; }
100%{ left: 960px; }
}
@-webkit-keyframes t3{
0%{ left: 1920px; }
20%{ left: 1920px; }
25%{ left: 960px; }
45%{ left: 960px; }
50%{ left: 0; }
70%{ left: 0; }
75%{ left: -960px; }
95%{ left: -960px; }
100%{ left: 1920px; }
}
@-webkit-keyframes t4{
0%{ left: 2880px; }
20%{ left: 2880px; }
25%{ left: 1920px; }
45%{ left: 1920px; }
50%{ left: 960px; }
70%{ left: 960px; }
75%{ left: 0; }
95%{ left: 0; }
100%{ left: 2880px; }
}
这里定义了 t1、t2、t3、t4 四个动画名称,主要是动画里的帧数的设置技巧,因为只有4张图,所以就取每次帧数增加 25% 的时候才让 left 值减去图片宽度,而在改变 left 值之前的 5%(这个值根据情况调整)处 left 值保持不变,而这个 5% 表示的就是轮播图中图片移动的时间,另外 20% 表示的就是图片禁止的状态。然后把这4个自定义动画一一放到每一个 img 里,例如:
.test .img1{
left: 0;
-webkit-animation: t1 linear 12s infinite;
-moz-animation: t1 linear 12s infinite;
-ms-animation: t1 linear 12s infinite;
-o-animation: t1 linear 12s infinite;
animation: t1 linear 12s infinite;
}
.test .img2{
left: 960px;
-webkit-animation: t2 linear 12s infinite;
-moz-animation: t2 linear 12s infinite;
-ms-animation: t2 linear 12s infinite;
-o-animation: t2 linear 12s infinite;
animation: t2 linear 12s infinite;
}
.test .img3{
left: 1920px;
-webkit-animation: t3 linear 12s infinite;
-moz-animation: t3 linear 12s infinite;
-ms-animation: t3 linear 12s infinite;
-o-animation: t3 linear 12s infinite;
animation: t3 linear 12s infinite;
}
.test .img4{
left: 2880px;
-webkit-animation: t4 linear 12s infinite;
-moz-animation: t4 linear 12s infinite;
-ms-animation: t4 linear 12s infinite;
-o-animation: t4 linear 12s infinite;
animation: t4 linear 12s infinite;
}
.test:hover img{
-webkit-animation-play-state: paused;
-moz-animation-play-state: paused;
-ms-animation-play-state: paused;
-o-animation-play-state: paused;
animation-play-state: paused;
}
代码最后给了一个鼠标移上去,动画停止的效果,整个轮播的时间自行设置,‘infinite’ 表示一直持续轮播。
您可能感兴趣的文章:
CSS实现轮播图广告效果
基于jquery实现图片广告轮换效果代码
基于jQuery的仿flash的广告轮播代码
基于jQuery的仿flash的广告轮播
图片轮播插件 Image rotator
12款经典的白富美型—jquery图片轮播插件—前端开发必备
jQuery图片轮播的具体实现
jQuery 焦点新闻图片轮播的实现代码
基于jquery的图片轮播 tab切换组件
jquery 图片轮播代码示例