Home > Article > Web Front-end > Implementing image carousel based on javascript array_javascript skills
There are many ways to carousel images. Here is a simple one: js array implementation.
First store the image path in the array, and then call the setInterval function to rotate the images in sequence
<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>
The complete example is as follows
<!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>
The above is the entire content of this article, I hope it will be helpful to everyone’s study.