Home > Web Front-end > JS Tutorial > Implementing image carousel based on javascript array_javascript skills

Implementing image carousel based on javascript array_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 15:02:38
Original
1868 people have browsed it

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>
Copy after login

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>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Where is js written?
From 1970-01-01 08:00:00
0
0
0
js addClass not working
From 1970-01-01 08:00:00
0
0
0
js file code not found
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template