麻烦改变与javascript定时器图像

Trouble changing images with a timer with javascript

本文关键字:定时器 图像 javascript 改变 麻烦      更新时间:2023-09-26

我正在写一个网站,我想通过计时器上的各种图像动画。我有一个数组列出了每个图像(作为用于构建filename的数字)。动画应该遍历这些数字,然后依次改变图像。

<img id="myImg"  src=" http://old.ycombinator.com/images/yc500.gif" width ='100' height='100'/>
<script>
var myImages = [1, 2, 3, 5]
var img_index = 0;
var timer;
var imgId = "myImg";
// Bind the image onload event like this:
document.getElementById(imgId).onload = animate();
// Start animation
function animate() {
    me = document.getElementById(imgId);
    me.src = "coolimg." + myImages[img_index] + ".jpg"
    img_index++;
    if (img_index == myImages.length){
        img_index = 0;
    }
    timer = setTimeout(animate, 1000);
}
</script>