1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>轮播图</title> 6 <style type="text/css"> 7 *{ 8 margin: 0; 9 padding:0; 10 } 11 .carousel{ 12 margin:0 auto; 13 width:400px; 14 height: 300px; 15 position: relative; 16 } 17 span{ 18 width:20px; 19 height:20px; 20 background: rgba(0,0,0,.6); 21 border-radius: 50%; 22 } 23 a{ 24 text-decoration: none; 25 color:#fff; 26 } 27 p{ 28 width:200px; 29 text-align: center; 30 line-height: 20px; 31 position: absolute; 32 top:260px; 33 left:100px; 34 display: flex; 35 justify-content: space-around; 36 } 37 </style> 38 <script type="text/javascript"> 39 window.onload =function () { 40 var aNode = document.getElementsByTagName("a"); 41 var divNode = document.getElementsByTagName("div")[0]; 42 var imgNode = document.createElement("img"); 43 for (var position in aNode) { 44 aNode[position].onclick = function () { 45 var index = this.innerText; 46 carousel(index); 47 } 48 } 49 function carousel(index) { 50 imgNode.src = 'images/' + index + '.jpg' + '/'; 51 divNode.appendChild(imgNode); 52 } 53 var i = 1; 54 imgNode.src = 'images/' + i + '.jpg' + '/'; 55 function change() { 56 imgNode.src = 'images/' + i + '.jpg' + '/'; 57 i++; 58 if (i == 7) { 59 i = 1; 60 } 61 } 62 divNode.appendChild(imgNode); 63 setInterval(change, 1500); 64 } 65 </script> 66 </head> 67 <body> 68 <div class="carousel"> 69 <p> 70 <span><a href="#" onclick="carousel(1)">1</a></span> 71 <span><a href="#" onclick="carousel(2)">2</a></span> 72 <span><a href="#" onclick="carousel(3)">3</a></span> 73 <span><a href="#" onclick="carousel(4)">4</a></span> 74 <span><a href="#" onclick="carousel(5)">5</a></span> 75 <span><a href="#" onclick="carousel(6)">6</a></span> 76 </p> 77 </div> 78 </body> 79 </html>
注意:图片需要自己去添加images文件,大小我用的是400*300,可以更改的!
还有其他方法使用js实现轮播图,比如点击以后让图片transform:translate;点击后改变其display,点击后改变z-index,不点击让他自己产生动态移动就是使用:setInterval
技术不重要,重要的是思想!