我正在尝试移动 <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/