需求:
循環無縫自動輪播3張圖片,點擊左右箭頭可以手動切換圖片,鼠標點擊輪播圖下面的小圓點會跳轉到對應的第幾張圖片。鼠標放到輪播圖的圖片上時不再自動輪播,鼠標移開之后又繼續輪播。
效果圖:
下面是html代碼:
<div id="box"> <div id="imgbox"> <div><img src="img/tu1.jpg" alt="" /></div> <div><img src="img/tu2.jpg" alt="" /></div> <div><img src="img/tu3.jpg" alt="" /></div> </div> <div class="yuandian"> <a href="#" class="xiaoyuan"></a> <a href="#" class="xiaoyuan"></a> <a href="#" class="xiaoyuan"></a> </div> <div id="jiantou"> <span id="jt_left" class="jiant"><</span> <span id="jt_right" class="jiant">></span> </div> </div>
css代碼:
* { margin: 0; padding: 0; } #box { position: relative; width: 520px; height: 280px; /*background-color: pink;*/ margin:100px auto; overflow: hidden; } #imgbox { position: absolute; top: 0; left: 0; width: 99999px; cursor: pointer; height: 100%; } #imgbox img { float: left; } .yuandian { position: absolute; left: 230px; bottom: 20px; width: 60px; height: 15px; border-radius: 20px; background: rgba(255,255,255,.6); } .yuandian a { float: left; width: 10px; height: 10px; border-radius: 10px; margin: 2px 0 0 7px; background-color: white; } #jt_left { left: 0; border-top-right-radius:2em; border-bottom-right-radius:2em; } #jt_left, #jt_right { position: absolute; top: 140px; width: 35px; height: 35px; line-height: 35px; cursor: pointer; font-size: 18px; text-align: center; background: rgba(255,255,255,.6); } #jt_right { right: 0; border-top-left-radius:2em; border-bottom-left-radius:2em; }
js代碼:
<script type="text/javascript"> // 獲取小圓點 var xiaoyuan = document.getElementsByClassName("xiaoyuan"); // 獲取裝圖片的盒子 var imgbox = document.getElementById("imgbox"); // 獲取左右箭頭 var jiantou = document.getElementsByClassName("jiant"); //小圓點控制圖片 xiaoyuan[0].onclick = function () { imgbox.style.left = 0; } xiaoyuan[1].onclick = function () { imgbox.style.left = "-520px"; } xiaoyuan[2].onclick = function () { imgbox.style.left = "-1040px"; } //左箭頭控制圖片 jiantou[0].onclick = function () { if (imgbox.offsetLeft == 0) { imgbox.style.left = "-1040px"; console.log(imgbox.offsetLeft); } else { imgbox.style.left = imgbox.offsetLeft + 520 + "px"; } } //右箭頭控制圖片 jiantou[1].onclick = function () { if (imgbox.offsetLeft <= -1040) { console.log(imgbox.offsetLeft); imgbox.style.left = 0; } else { imgbox.style.left = imgbox.offsetLeft - 520 + "px"; } } //定時器控制圖片輪播 var fun1 = function () { if (imgbox.offsetLeft <= -1040) { imgbox.style.left = 0; } else { imgbox.style.left = imgbox.offsetLeft - 520 + "px"; } } var t = setInterval(fun1, 2500);//fun1是你的函數 // 鼠標經過停止輪播 imgbox.onmouseover = function () { clearInterval(t) //關閉定時器 } // 鼠標離開開啟定時器 imgbox.onmouseout = function () { t=setInterval(fun1,2500)//重新開始定時器 } </script>