gpt4 book ai didi

javascript - 为什么 setTimeout 没有按预期工作?

转载 作者:行者123 更新时间:2023-11-30 09:58:39 25 4
gpt4 key购买 nike

我正在尝试移动 <div id="box">每次我的鼠标指针悬停在它上面,但它似乎只有在我有 mouseover 时才会移动div 上的事件,而不是当我的鼠标悬停在它上面时。

document.getElementsByTagName("body")[0].addEventListener("load",init());

function init(){
console.log('in init');
document.getElementById("box").addEventListener("mouseover",function(){
var pixels=5;
var perMs=40;
var repeater=setTimeout(moveBox(pixels),perMs);

document.getElementById("box").addEventListener("mouseout",function(){
console.log('mouseOut');
clearTimeout(repeater);
});

});

}

function moveBox(pixels){

console.log('moveBox');
var leftBox=document.getElementById("box").style.left;
leftBox=parseInt(leftBox)+pixels;
document.getElementById("box").style.left=leftBox;

}

最佳答案

看起来好像您打算使用 setInterval 来重复调整元素:

var repeaterId = setInterval(moveBox, perMs, pixels);

阅读更多相关信息 here .

关于javascript - 为什么 setTimeout 没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32725169/

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