原理:主要运用z-index这个属性来设置图片的展示和隐藏,代码如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>zIndex制作轮播图</title> 6 <style> 7 html,body,ul,li,input{margin: 0;padding: 0} 8 .box1{ 9 width: 520px; 10 height: 280px; 11 margin: 0 auto; 12 position: relative; 13 border:1px solid black; 14 } 15 ul{ 16 width: 520px; 17 height: 280px; 18 position: relative; 19 } 20 ul li{ 21 position: absolute; 22 list-style: none; 23 } 24 ul li a{ 25 display: block; 26 width: 520px; 27 height: 280px; 28 } 29 .btn1{ 30 position: absolute; 31 width: 48px; 32 height: 60px; 33 background: url(btn.png) no-repeat; 34 border:0; 35 left: 0; 36 top:110px; 37 cursor: pointer; 38 z-index: 10000; 39 } 40 .btn2{ 41 position: absolute; 42 width: 48px; 43 height: 60px; 44 background: url(btn.png) no-repeat -48px; 45 border:0; 46 right: 0; 47 top:110px; 48 cursor: pointer; 49 z-index: 10000; 50 } 51 </style> 52 <script> 53 window.onload = function(){ 54 var btn1 = document.getElementsByClassName("btn1")[0]; 55 var btn2 = document.getElementsByClassName("btn2")[0];//有兼容问题 56 var liList = document.getElementsByTagName("ul")[0].children; 57 var index = 1; 58 var i = 4; 59 btn1.onclick = function(){ 60 i++; 61 if(i == 5){ 62 i = 0; 63 } 64 liList[i].style.zIndex = index++; 65 } 66 btn2.onclick = function(){ 67 i--; 68 if(i == -1){ 69 i = 4; 70 } 71 liList[i].style.zIndex = index++; 72 } 73 var timer = setInterval(function(){btn2.onclick();},1000) 74 } 75 </script> 76 </head> 77 <body> 78 <div class="box1"> 79 <ul> 80 <li><a href=""><img src="5.jpg" alt=""></a></li> 81 <li><a href=""><img src="4.jpg" alt=""></a></li> 82 <li><a href=""><img src="3.jpg" alt=""></a></li> 83 <li><a href=""><img src="2.jpg" alt=""></a></li> 84 <li><a href=""><img src="1.jpg" alt=""></a></li> 85 </ul> 86 <input type="button" name="" class="btn1" /> 87 <input type="button" name="" class="btn2" /> 88 </div> 89 </body> 90 </html>
问题:在这里我们加了一个定时器来让图片自己切换,当我们点击按钮的时候需要关闭定时器,这个可以通过clearInterval(timer)来实现,但是当我们不点击按钮的时候,想让定时器接着我们现在的图片自动轮播下去,这个问题如何解决呢?重新开定时器吗?
时间: 2024-11-09 00:38:33