gpt4 book ai didi

javascript - 在同一页面上更改多个图像

转载 作者:行者123 更新时间:2023-11-29 22:03:35 24 4
gpt4 key购买 nike

我正在使用此脚本在鼠标悬停时循环浏览图像。如何在同一页面上使用多张图片?

<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(...) 函数在将 1 添加到 index 参数时调用自身(递归)。这实现了与您的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com