时间:2020-10-18 11:25:51 | 栏目:JavaScript代码 | 点击:次
本文实例为大家分享了javascript图片轮播效果的具体代码,供大家参考,具体内容如下
<!DOCTYPE HTML> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>图片轮播</title> <style> #box { width:506px; height:306px; margin: 20px auto; border:3px solid black; position:relative; background-color:orange; overflow: hidden; /*overflow: hidden;*/ } .pic { position: absolute; width:500px; height:300px; line-height: 300px; text-align: center; font-size: 100px; color:white; bottom:0; } .red { background-color:red; } .green { background-color:green; } .blue { background-color:blue; } .orange{ background-color: orange; } .move { bottom:300px; transition:bottom 3s; /* 设置图片移动消耗的时间*/ } </style> </head> <body> <div id="box"> <div id="pic1" class="pic red">1</div> <div id="pic2" class="pic green">2</div> <div id="pic3" class="pic blue">3</div> <div id="pic3" class="pic orange">4</div> </div> <script> window.addEventListener('load',function(){ var pics = document.getElementsByClassName('pic'); //为每个pic元素设置z-index的值 for(let i=0;i<pics.length;i++){ pics[i].style.zIndex = pics.length-i; } //循环播放图片的函数 var loopPics = (function(){ var index=0; return function(pics,delay){ var recall = function(pic){ //给图片增加move类,调用css的transition属性播放移动动画 pic.className += ' move'; setTimeout(function(){ //取消图片的move类,图片返回原位 pic.className=pic.className.replace(' move',''); //改变图片组的堆叠顺序。最外的图片放到最下面,其他图片依次向外移动 for(let i=0;i<pics.length;i++){ if(pics[i].style.zIndex==pics.length){ pics[i].style.zIndex=1; } else { pics[i].style.zIndex=pics[i].style.zIndex*1+1; } } index++; if(index==pics.length) index=0; recall(pics[index]); },delay); }; recall(pics[index]); }; })(); //调用函数,循环播放。delay的时间需要大于等于css动画里设置的图片移动时间 loopPics(pics,4000); }); </script> </body> </html>