我每次将鼠标指针悬停在它上面时都会尝试移动<div id="box">
,但它似乎只在div上有mouseover
事件时移动,而不是当鼠标悬停在它上面时才会移动。为什么setTimeout不按预期工作?
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;
}
'阅读进度(“负荷”,INIT);'你想通过函数本身,不运行它并传递它的返回值。 –
可能重复的[javascript - setTimeout返回](http://stackoverflow.com/questions/7142010/javascript-settimeout-return) –
我试过传递函数像这样document.getElementsByTagName(“body”)[0] .addEventListener (“负载”,()的函数 ,但仍然无法正常工作 – Snedden27