gpt4 book ai didi

javascript - 为什么我的函数在所有创建的元素上运行?

转载 作者:行者123 更新时间:2023-11-29 18:50:40 25 4
gpt4 key购买 nike

我已经编写了一个基本函数(庆祝),它在我的页面上运行 onmouseenter 链接。

它创建一个 p 元素,然后调用一个函数 (move) 将元素从页面的右侧移动到左侧。

即使鼠标离开元素,我也希望此移动函数运行。

不幸的是,当您鼠标移开时,不仅移动的文本会消失,而且所有链接都以相同的速度移动。如果一个元素开始移动并且您将鼠标悬停以创建一个新的移动元素,它会将两个移动元素移回右侧并将它们移动到彼此成一直线。

我知道我的代码有问题,但我不知道是什么:)

function celebrate(link) {
let celebration = document.createElement("p");
let celebrationtext = document.createTextNode(link.text);
celebration.appendChild(celebrationtext);
document.body.appendChild(celebration);
celebration.className = 'moving';
celebration.style.top = link.getBoundingClientRect().top;
move(celebration, 1100);
}

function move(object, X){
let thisobject = object;
console.log(thisobject);
if ( object != null ) {
intX=X-3;
thisobject.style.left = (intX).toString() + 'px';
} //if
if ( X > 0 ) {
setTimeout(function(){move(thisobject,intX)},20);
} else {
thisobject.remove();
}
return true;
}

我使用 Eloquent Javascript 的章节标题创建了一个 JSfiddle

jsFiddle

最佳答案

那是因为你的 intX 是全局的,所有 move(thisobject,intX) 都使用它。

如果您在 move 函数内声明它会得到修复。

let thisobject = object,
intX;

更新的 fiddle :https://jsfiddle.net/63njmxrt/6/


或者您可以完全删除 intX 并在将其作为参数传递时减少 X

function move(object, X) {
let thisobject = object;

if (object != null) {
thisobject.style.left = (X).toString() + 'px';
} //if
if (X > 0) {
setTimeout(function() {
move(thisobject, X-3)
}, 20);
} else {
thisobject.remove();
}
return true;
}

关于javascript - 为什么我的函数在所有创建的元素上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380215/

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