2015-09-22 135 views
1

我每次将鼠标指针悬停在它上面时都会尝试移动<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; 

    } 
+1

'阅读进度(“负荷”,INIT);'你想通过函数本身,不运行它并传递它的返回值。 –

+0

可能重复的[javascript - setTimeout返回](http://stackoverflow.com/questions/7142010/javascript-settimeout-return) –

+0

我试过传递函数像这样document.getElementsByTagName(“body”)[0] .addEventListener (“负载”,()的函数 ,但仍然无法正常工作 – Snedden27

回答

3

看来好像你想用setInterval代替,以调节重复的基础上的元素:

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

了解更多关于它here

+0

尝试的setInterval不太一样problm – Snedden27

+0

现在不工作它是关于如何通过像setInterval(moveBox(像素),perMs)相同的功能调用参数似乎并没有工作 – Snedden27

0

代码中的许多语法问题,在这里它是与主要问题纠正。

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

    function moveBox(pixels) { 
     console.log('moveBox', pixels); 
     var boxLeft = parseInt(box.style.left, 10) || 0; 
     box.style.left = (boxLeft + pixels) + 'px'; 
    } 

    box.addEventListener("mouseover", function() { 
     repeater = setTimeout(moveBox, perMs, pixels); 
    }); 

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

} 

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

请注意,setTimeout只被调用一次,它不会重复。

演示在这里:https://jsfiddle.net/vqgesj58/1/

如果你想你的盒子移动,而你的鼠标移动到它,我会更新的代码。

+0

还是同样的问题花花公子:( – Snedden27

+0

我更新的代码,它现在应该达到预期效果的'setTimeout' – saeraphin

1

setTimeout接收回调函数作为第一个参数,问题是moveBox(像素)执行该函数并返回它的结果,因此您应该将其包装到另一个函数中。

你也想从“鼠标移出”事件每次订阅它在你的鼠标悬停回调时间退订:

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



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

    }); 


} 
+0

试过这是行不通的 – Snedden27

相关问题