Home  >  Article  >  Web Front-end  >  基于CSS3淡入淡出效果的图片轮播_html/css_WEB-ITnose

基于CSS3淡入淡出效果的图片轮播_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-21 09:08:431759browse

网上的淡入淡出效果大多是依照jquery中fadeIn和fadeOut的思路使用js来控制元素的透明度达到目的,但缺点是有轻微的卡顿感,并且运行效率一般。 这里提供另外一个思路,即通过预先定义好的css样式老控制透明度的过渡, 这种方法过渡平滑,且因为过渡的效果是基于css3的animation,所以效率高些。 思路是将淡入,淡出的效果做成预先定义好的样式类,然后用JS改变元素的类来达到图片轮播,废话不多说,上代码:

在线DEMO展示
HTML:

<div id="imgs">  <div id="bg1" class="bg"></div>  <div id="bg2" class="bg"></div></div>

CSS:

.bg {  position: absolute;  left: 0;  top: 0;  width: 100vw;  height: 100vh;}#bg1 {  background: url(http://pfile.cn/11n0lc) no-repeat;  background-size: cover;  -webkit-transition: opacity 2s linear;  -moz-transition: opacity 2s linear;  -o-transition: opacity 2s linear;  transition: opacity 2s linear;}#bg2 {  background: url(http://pfile.cn/emebgq) no-repeat;  background-size: cover;  -webkit-transition: opacity 2s linear;  -moz-transition: opacity 2s linear;  -o-transition: opacity 2s linear;  transition: opacity 2s linear;}.fadein{    opacity:100;}.fadeout{    opacity:0;}

JS:

function fadeIn(e) {  e.className = "bg fadein"};function fadeOut(e) {  e.className = "bg fadeout"};cur_img = document.getElementById("imgs").children.length - 1;function turnImgs(imgs) {  var imgs = document.getElementById("imgs").children;  if (cur_img == 0) {    fadeOut(imgs[cur_img]);    cur_img = imgs.length - 1;    fadeIn(imgs[cur_img]);  } else {    fadeOut(imgs[cur_img]);    fadeIn(imgs[cur_img - 1]);    cur_img--;  }}setInterval(turnImgs, 2000);

demo中只用了两张图片,如果需要插入更多的图片,可以在id=“imgs”的的div中加入一个新的子div ,class加上bg即可,然后在CSS中加入该div的描述,比如HTML中加入

,然后CSS中则加入#bg2 {
background: url(图片地址) no-repeat;
background-size: cover;
-webkit-transition: opacity 2s linear;
-moz-transition: opacity 2s linear;
-o-transition: opacity 2s linear;
transition: opacity 2s linear;
} 即可。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn