gpt4 book ai didi

javascript - 将动画脚本应用于不同的 Div/img

转载 作者:行者123 更新时间:2023-11-27 23:52:17 24 4
gpt4 key购买 nike

需要在鼠标悬停时将 animateScript() 函数应用于不同的图像/div。我想我只需要更改我的 document.querySelector 但我不确定如何更改以使其适用于 4 个不同图像之一。

let tID; //we will use this variable to clear the setInterval()
//let x = event.clientX, y = event.clientY, elementMouseIsOver = document.elementFromPoint(x, y);

function stopAnimate() {
clearInterval(tID);
} //end of stopAnimate()

function animateScript() {
let position = 80; //start position for the image slicer
let height = 0;
const interval = 190; //180 ms of interval for the setInterval()
const diff = 80; //diff as a variable for position offset
const next_row = 110;
let elements = document.querySelectorAll(':hover');

tID = setInterval(() => {
document.querySelector(".avatar").style.backgroundPosition = `-${position}px -${height}px`;
//we use the ES6 template literal to insert the variable "position"
if (height < 220)
{
if (position < 720) {
position = position + diff;
console.log(position);
}
else if (position == 720){
//console.log("height");
position = 80;
height = next_row + height;
console.log("height: ", height);
}
}
else {
if (position < 400) {
position = position + diff;
console.log(position);
}
else if (position == 480){
position = 80;
height = 0;
console.log("height: ", height);
}
}
//reset the position to 256px, once position exceeds 1536px
}, interval); //end of setInterval
} //end of animateScript()

最佳答案

您正在对 .avatar 选择器进行硬编码,它将始终获得该类的第一个元素,因此您是正确的,需要更改。

一个简单的解决方案是将悬停元素传递到您的函数中。

const handleMouseEnter = (e) => {
const el = e.target;
animateScript(el);
}

element.addEventListner("mouseenter", handleMouseEnter);

function animateScript(element) {
[...]
tID = setInterval(() => {
element.style.backgroundPosition = `whatever style`;
[...]
}, interval);
}

关于javascript - 将动画脚本应用于不同的 Div/img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56450914/

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