圖片輪播的辦法有多種,在這裡介紹一種簡單的:js數組實作。
先將圖片路徑儲存在陣列中,然後再呼叫setInterval函數來依序輪播圖片
<script type="text/javascript"> var curIndex = 0; var timeInterval = 1000; var arr = new Array(); arr[0] = "1.png"; arr[1] = "2.png"; arr[2] = "3.png"; arr[3] = "4.png"; arr[4] = "5.png"; setInterval(changeImg,timeInterval); function changeImg() { var obj = document.getElementById("imge"); if (curIndex == arr.length-1) { curIndex = 0; } else { curIndex += 1; } obj.src = arr[curIndex]; } </script>
完整實例如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用数组实现图片自动轮播</title> <style type="text/css"> #main{ width: 700px; height: 450px; margin: 0 auto; text-align: center; } </style> <script type="text/javascript"> var curIndex = 0; var timeInterval = 1000; var arr = new Array(); arr[0] = "1.png"; arr[1] = "2.png"; arr[2] = "3.png"; arr[3] = "4.png"; arr[4] = "5.png"; setInterval(changeImg,timeInterval); function changeImg() { var obj = document.getElementById("imge"); if (curIndex == arr.length-1) { curIndex = 0; } else { curIndex += 1; } obj.src = arr[curIndex]; } </script> </head> <body> <div id="main"> <h1>使用数组实现图片自动轮播</h1> <img id = "imge" src = "1.png" alt="picture" /> </div> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助。