图像不改变后给定的时间在java脚本

images are not changing after given time in java Script

本文关键字:时间 java 脚本 改变 图像      更新时间:2023-09-26
<!Doctype html>
<html>
  <head>
    <title>Slider</title>
      <style>
      </style>
    </head>
    <body>
      <img id="text" alt="picture" src="cod4.jpg" style="width:900px;height:500px;">
      <script>
        var images = [];
        images[0]= "cod2.jpg";
        images[1]= "cod3.jpg";
        images[2]= "cod4.jpg";
        setInterval(changeimage,3000)
        function changeimage(){
        for(var i=0; i<=images.length; i++)
        {
          document.getElementById("text").src += images[i] ;
        }
      }
    </script>
  </body>
</html>

在java Script中给定时间后图像不会改变。我试图在3秒后改变图像,但它不工作

请告诉我这段代码有什么问题?由于

Artem Baranovskii发表了一个很棒的答案。我不确定你是否想让图像不断循环,所以我会把这个作为我的答案。

var images=["http://placehold.it/150x150","http://placehold.it/170x170","http://placehold.it/190x190"];
var i=0;
//Set image and interval when the page has loaded (Is ready). 
window.onload=function(){
//Call changeimage to set the first image.
changeimage();
//Set interval
setInterval(changeimage,3000);
}
function changeimage(){
//Check if i is equal  to or "||" greater than array length.
if(i==images.length||i>images.length){
//If true, reset i to 0. Back to the first image in the array
	i=0;
}
//Set the image url.
document.getElementById('text').src=images[i];
//Add 1 to i. 
i++;
}
<img id="text" src=""/>

源代码中的注释,但如果您有任何问题,请在下面留下评论,我会尽快回答。

我希望这对你有帮助。编码快乐!

完整源代码。

<!DOCTYPE html>
<html>
<head>
<title>Slider</title>
<script type="text/javascript">
var images=["http://placehold.it/150x150","http://placehold.it/170x170","http://placehold.it/190x190"];
var i=0;
window.onload=function(){
changeimage();
setInterval(changeimage,3000);
}
function changeimage(){
if(i==images.length||i>images.length){
    i=0;
}
document.getElementById('text').src=images[i];
i++;
}
</script>
</head>
<body>
<img id="text" src=""/>
</body>
</html>

尝试以下代码:

var images = ["cod2.jpg", "cod3.jpg", "cod4.jpg"],
    timer;
function changeimage() {
  var nextImage = images.shift();
  if (!nextImage) {
     clearInterval(timer);
     return;
  }
  document.getElementById("text").src = nextImage; 
}
timer = setInterval(changeimage, 3000)

EDIT根据您的代码更改:

<!doctype html>
  <html>
    <head>
      <title>Slider</title>
    </head>
    <body>
       <img id="text" alt="picture" src="cod4.jpg" style="width:900px;height:500px;" />
       <script>
         var images = [], timer;
         images.push("cod2.jpg");
         images.push("cod3.jpg");
         images.push("cod4.jpg");
         function changeimage(){
           var nextImage = images.shift();
           if (!nextImage) {
              clearInterval(timer);
              return;
           }
           document.getElementById("text").src = nextImage; 
         }
         timer = setInterval(changeimage, 3000)
       </script>    
   </body>
</html>