javascript - 3 秒后切换 Img Source

标签 javascript html

我有一个 img,我有一个 javascript 代码可以在 3 秒后更改 img 的源,我的问题是,在更改源并渲染 3 个图像后,它不会再次显示第一张图片,所以我猜猜是不是在循环?有人可以帮我解决这个问题吗?谢谢!

HTML

<img id="graphics" src="images/graphic1.svg" />

JavaScript

<script type = "text/javascript">
(function() {     // function expression closure to contain variables
    var i = 0;
    var pics = [ "graphic1.svg", "graphic2.svg", "graphic3.svg" ];
    var el = document.getElementById('graphics');  // el doesn't change

    function toggle() {
        el.src = pics[i];           // set the image
        i = (i + 1) % pics.length;  // update the counter
    }

    setInterval(toggle, 3000);
})();             // invoke the function expression
</script>

最佳答案

循环成功

我测试了你的代码,循环没问题。

CodePen Test

(function() { // function expression closure to contain variables
var i = 0;
var pics = ["http://placehold.it/200x100/f00/fff.png", "http://placehold.it/200x100/f0f/000.png", "http://placehold.it/200x100/333/999.png"];
var el = document.getElementById('graphics'); // el doesn't change
function toggle() {
    el.src = pics[i]; // set the image
    i = (i + 1) % pics.length; // update the counter
}
setInterval(toggle, 3000);
})(); // invoke the function expression

检查图片路径

问题可能出在您的图片路径上。您可能需要将 images/ 附加到 src

关于javascript - 3 秒后切换 Img Source,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35347885/

相关文章:

javascript - 无法读取未定义 jquery 滚动的顶部

javascript - 如何在php中直接通过查询字符串传递文本框值

javascript - JQuery 滑动开关 :visible conditional

Javascript将div添加到另一个div的顶部

jquery - 使用 CSS 更改移动设备上的 HTML 布局

JavaScript 隐藏类似于密码的纯文本

jquery - 使用 jQuery 将列自动调整为具有相同的高度

javascript - ReactJS 表单字段的值未更新,并记录为日期字段

javascript - 在将其放入 DOM 之前初始化 jQuery 对象(元素)

javascript - Matter JS - event.pairs 数组在碰撞时为空