我试图每次将鼠标指针悬停在<div id="box">上时,但仅当我在div上具有mouseover事件时才移动,而当鼠标悬停在它上时,它似乎不会移动。

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/

10-09 19:38