javascript - 在 javaScript 中给定时间后图像没有改变

标签 javascript css html image

<!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 脚本中的给定时间后没有改变。 我尝试在 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=""/>

Comments in the source code but if you have any questions please leave a comment below and I will answer as soon as possible.

希望对您有所帮助。编码愉快!

Full source code.

<!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>

关于javascript - 在 javaScript 中给定时间后图像没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31776574/

相关文章:

javascript - Vue.js 3 : a `v-model` looses reactivity when `data()` converted to `setup()`

javascript - 当我刷新我的页面时,CSS 渲染了一个奇怪的矩形

css - 什么是行高 :1?

javascript - 如何在移动设备中将 Bootstrap 中的控件设置为全高(带滚动、固定页眉/页脚)

html - 如何在 Ionic 的正中心制作带有图像和文本的 div?

javascript - 使用组元素而不是点时数据丢失

Javascript模态窗口调用函数-bootstrap UI

html - 将所有带有输入字段的分隔线从左到右并排布置,然后使标 checkout 现在输入字段的顶部

css - index.html 中的 main.css 文件引用指向一个 main.scss 文件

html - 找不到处理程序引用的错误静态文件 : dist/api/landing for Angular App deployed on Google Cloud