我有一个 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>
最佳答案
循环成功
我测试了你的代码,循环没问题。
(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/