我有一个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>
答案 0 :(得分:2)
我测试了你的代码,循环没问题。
(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 。