JavaScript輪播圖的實現 HTML部分: CSS部分 JavaScript部分 ...
JavaScript輪播圖的實現
HTML部分:
1 <!-- HTML部分 --> 2 <!DOCTYPE html> 3 <html> 4 <head> 5 <meta charset="utf-8"> 6 <title>輪播圖</title> 7 <link rel="stylesheet" type="text/css" href="css/demo06.css"/> 8 <script src="js/demo06.js"></script> 9 </head> 10 <body> 11 <div class="container"> 12 <!-- 輪播圖區域 --> 13 <ul class="lbimg"> 14 <li class="on" style="background-color: #898989;">輪播圖1</li> 15 <li style="background-color: #CD282B;">輪播圖2</li> 16 <li style="background-color: pink;">輪播圖3</li> 17 <li style="background-color: peachpuff;">輪播圖4</li> 18 <li style="background-color: palegoldenrod;">輪播圖5</li> 19 </ul> 20 <ol class="btn"> 21 <li class="active">第1張</li> 22 <li>第2張</li> 23 <li>第3張</li> 24 <li>第4張</li> 25 <li>第5張</li> 26 </ol> 27 </div> 28 </body> 29 </html>
CSS部分
1 *{ 2 margin: 0; 3 padding: 0; 4 list-style: none; 5 } 6 .container{ 7 width: 600px; 8 height: 400px; 9 border: 4px double #FF6633; 10 margin: 0 auto; 11 } 12 13 /* 輪播圖 */ 14 .lbimg li{ 15 width: 100%; 16 height: 350px; 17 text-align: center; 18 line-height: 350px; 19 display: none; 20 font-size: 25px; 21 color: #FF6633; 22 } 23 .lbimg .on{ 24 display: block; 25 } 26 27 .btn{ 28 width: 100%; 29 height: 50px; 30 background-color: #3CBDFF; 31 display: flex; 32 } 33 .btn li{ 34 flex: 1; 35 color: #fff; 36 font-weight: bold; 37 line-height: 50px; 38 text-align: center; 39 font-family: "楷體"; 40 cursor: pointer; 41 42 } 43 .btn .active{ 44 background-color: rgba(0,0,0,0.2); 45 transition: all ease-in-out 0.25s; 46 }
JavaScript部分
1 window.onload=function(){ 2 var lbimg=document.querySelector(".lbimg"); 3 var lbimgs=lbimg.querySelectorAll("li"); 4 var btn=document.querySelector(".btn"); 5 var btns=btn.querySelectorAll("li"); 6 7 for (var i = 0; i < btns.length; i++) { 8 9 btns[i].index=i; 10 btns[i].onclick=function(){ 11 clearInterval(timer); 12 for (var j = 0; j < lbimgs.length; j++) { 13 lbimgs[j].className=""; 14 } 15 // 按鈕顏色跟著變化 16 for(var k=0;k<btns.length;k++){ 17 btns[k].className=""; 18 } 19 // 輪播同步,點擊後圖片的位置從點擊的地方開始輪播 20 index=this.index; 21 btns[this.index].className="active"; 22 lbimgs[this.index].className="on"; 23 timer=setInterval(autoPlay,1000); 24 } 25 } 26 var index=0; 27 // 自動輪播 28 index++; 29 var timer=setInterval(autoPlay,1000); 30 function autoPlay(){ 31 for (var i = 0; i < lbimgs.length; i++) { 32 lbimgs[i].className=""; 33 } 34 for (var j = 0; j < btns.length; j++) { 35 btns[j].className=""; 36 } 37 if(index==lbimgs.length-1){ 38 index=0; 39 }else{ 40 index++; 41 } 42 btns[index].className="active"; 43 lbimgs[index].className="on"; 44 } 45 46 // 滑鼠移動時清除定時器 47 lbimg.onmouseover=function(){ 48 clearInterval(timer); 49 } 50 lbimg.onmouseout=function(){ 51 timer=setInterval(autoPlay,1000); 52 } 53 54 }