Javascript 在同一页上更改多个图像

Javascript 在同一页上更改多个图像,javascript,Javascript,我使用这个脚本在鼠标上方的图像中循环。如何使同一页上的多张图片都能使用此功能 <script> var myImages = [1, 2, 3] var img_index = 0; var timer; var imgId = "myImg"; // Start animation function animate() { me = document.getElementById(imgId); me.src = "Pictures/" + "test" +

我使用这个脚本在鼠标上方的图像中循环。如何使同一页上的多张图片都能使用此功能

<script>
var myImages = [1, 2, 3]
var img_index = 0;
var timer;
var imgId = "myImg";

// Start animation
function animate() {
    me = document.getElementById(imgId);

    me.src = "Pictures/" + "test"  + myImages[img_index] + ".png"

    img_index++;

    if (img_index == myImages.length){
        img_index = 0;
    }
     timer = setTimeout(animate, 500);

}

function stopAnimation() {
    clearTimeout(timer);
   me.src="Pictures/test1.png"
}
</script>

<img class= "format" id="myImg" onmouseover="imgId = this.id; timer = setTimeout(animate, 1000);" onmouseout="stopAnimation();" src="Pictures/test1.png" />

var myImages=[1,2,3]
var img_指数=0;
无功定时器;
var imgId=“myImg”;
//启动动画
函数animate(){
me=document.getElementById(imgId);
me.src=“Pictures/”+“test”+myImages[img_index]+.png”
img_索引++;
if(img_index==myImages.length){
img_指数=0;
}
定时器=设置超时(动画,500);
}
函数stopAnimation(){
清除超时(计时器);
me.src=“Pictures/test1.png”
}

您有一个特定于具体情况的功能,必须对该功能进行调整,才能使用任何给定的元素。为了做到这一点,您应该用局部变量(特别是函数参数)替换常量和全局变量。理想情况下,您需要一个可以接受HTML节点、数组和延迟时间的函数。此外,对于这个特定的问题,您可以使用递归来摆脱
var img_索引

我会这样做:

var myImages = [1, 2, 3];
var timeouts={};

// Start Animation of HTML object obj with images in array arr and a delay time.
function startAnimation(obj,arr,time){
   timeouts[obj.id] = setTimeout(function(){
      animate(this,arr,time,0);
   },time);
}
// Animate, index used to keep track of image number
function animate(obj,arr,time,index){
   obj.src = "Pictures/" + "test"  + arr[index] + ".png";
   timeouts[obj.id] = setTimeout(function(){
      animate(this,arr,time,(index==arr.length)?0:index++);
   },time);
}
// End the animation of HTML object obj
function stopAnimation(obj){
   clearTimeout(timeouts[obj.id]);
}
因为要将代码应用于多个动画,必须考虑使用多个数组(每个动画一个)的方法。这就是参数
arr
的作用。另外,您必须考虑不同的HTML元素(图像),这是争论“代码> Obj/<代码>的原因。如果向函数传递对对象的引用而不是id,则无需使用
document.getElementById(…)
。换句话说,动画函数使用的是对图像元素的引用,而不是其id。此外,您可能希望在动画之间改变时间延迟,这就是
time
参数的作用

animate(…)
函数在向
索引
参数添加一个参数时调用自身(递归)。这与
img_索引
变量相同,但没有附加变量

和HTML:

<img class="format" id="myImg" onmouseover="startAnimation(this,myImages,500)" onmouseout="stopAnimation(this);" src="Pictures/test1.png" />

对其进行重构,使其包含一些参数,并具有足够的通用性我是javascript新手。你能解释一下我是否需要在我的部分代码中使用你的代码,以及它是如何工作的吗?@A片:我编辑了这篇文章。希望它现在更有意义。代码应该按原样工作,而不添加任何部分。
document.getElementById("myImg").onmouseover = function(){
   startAnimation(this,myImages,500)
}
document.getElementById("myImg").onmouseout = function(){
   stopAnimation(this)
}