圖片輪播的辦法有多種,在這裡介紹一種簡單的: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>
以上就是本文的全部內容,希望對大家的學習有所幫助。