另辟蹊徑實現輪播圖的方法:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- jquery網絡引用地址 --> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <title> 兩個定時器實現輪播圖</title> </head> <body> <img id="app" src="./images/1.jpg" /> <br /> <button id="clear">停止輪播</button> <button id="continue">繼續輪播</button> <button id="pre">上一張</button> <button id="next">下一張</button> <script> //要遍歷的圖片路徑數組 var images = ['./images/1.jpg', './images/2.jpg', './images/3.jpg']; //獲取圖片對象 var image = document.getElementById("app"); //下標 var index = 0; //定時器 var interval, timeOut = 0; $(function () { // 綁定清除兩個定時器的方法 $("#clear").click(function () { console.log('清除定時器'); window.clearInterval(interval); window.clearTimeout(timeOut); }); // 對兩個定時器進行重新賦值 $("#continue").click(function () { console.log('繼續執行定時器'); interval = setInterval(function () { timeOut = setTimeout(() => { if (index > (images.length - 1)) { index = 0; } image.src = images[index]; index++; }, 1000); }, 1500); }); // 根據下標切換圖片 $("#next").click(function () { console.log('下一張') index++; if (index > (images.length - 1)) { index = 0; } image.src = images[index]; }); // 根據下標切換圖片 $("#pre").click(function () { console.log('上一張') index--; if (index < 0) { index = images.length - 1; } image.src = images[index]; }); // 默認執行主體 interval = setInterval(function () { timeOut = setTimeout(() => { if (index > (images.length - 1)) { index = 0; } image.src = images[index]; index++; }, 1000); }, 1500); }); </script> </body> </html>
項目結構: