时间:2021-01-02 15:12:13 | 栏目:JavaScript代码 | 点击:次
图片轮播的办法有多种,在这里介绍一种简单的: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>
精彩专题分享:jQuery图片轮播 JavaScript图片轮播 Bootstrap图片轮播
以上就是本文的全部内容,希望对大家的学习有所帮助。