我正在使用此脚本在鼠标悬停时循环浏览图像。如何使该功能适用于同一页面上的多张图片?
<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" />
最佳答案
您有一个特定于案例的函数,必须对其进行调整才能适用于任何给定的元素。为此,您应该用局部变量(特别是函数参数)替换常量和全局变量。理想情况下,您需要一个可以接受 HTML 节点、数组和延迟时间的函数。此外,对于这个特定问题,您可以使用递归来消除 var img_index
。
我会这样做:
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(...)
函数调用自身(递归),同时向 index
参数添加 1。这实现了与 img_index
变量相同的效果,但没有额外的变量。
和 HTML:
<img class="format" id="myImg" onmouseover="startAnimation(this,myImages,500)" onmouseout="stopAnimation(this);" src="Pictures/test1.png" />
在本例中,变量 this
指向图像元素。一般来说,在处理事件时它指向触发事件的元素。
或者,您也可以使用 JavaScript 而不是内联分配事件处理程序:
document.getElementById("myImg").onmouseover = function(){
startAnimation(this,myImages,500)
}
document.getElementById("myImg").onmouseout = function(){
stopAnimation(this)
}
关于javascript - 更改同一页面上的多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212839/