2010-10-19 76 views
13

當鼠標懸停在DOM對象上時,是否有JavaScript或jQuery解決方案來重複運行函數(在setTimeout之後)?否則說,有沒有JavaScript的「做鼠標懸停」(或「如果鼠標懸停」)?JavaScript/jQuery中的「if mouseover」或「do while mouseover」

$('someObject').bind('mouseover', function() { 

     //Do the following while mouseover 
     $('someOtherObject').css('margin-left',adjustedLeft + 'px'); 
     setTimeout(/*do it again*/,25); 

    }); 

回答

38
$('someObject').on('mouseenter', function() { 
    this.iid = setInterval(function() { 
     // do something   
    }, 25); 
}).on('mouseleave', function(){ 
    this.iid && clearInterval(this.iid); 
}); 

Example Look here

+0

+1,試圖爲此寫一個解釋.. – 2010-10-19 07:59:22

+0

+1清晰而簡單。 – jensgram 2010-10-19 08:01:15

+0

哦,這很酷!太好了! – Kyle 2010-10-19 08:09:58

0

我會使用onmouseout事件解決這個問題。 當鼠標懸停在mouseover事件的指定組件上時,開始您想要執行的任何操作。 當發生onmouseout事件時,我會停止它。

0

我使用jQuery的新的綁定風格。

 
$(el).bind({ 
'mouseenter': function(){console.log('Mouse over');}, 
'mouseleave': function(){console.log('Mouse leave');} 
}); 
0

我知道這是一種舊的,但我認爲正確的功能已經在JavaScript中,onmousemove做到了這一點。