3秒后切换Img Source

时间:2016-02-11 19:05:29

标签: 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>

1 个答案:

答案 0 :(得分:2)

循环确定

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

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