每10毫秒检查鼠标是否仍然hover元素的函数(如果是,则运行一个函数)

我想知道是否有一个函数在一个元素(例如div class =“myiv”)hover之后运行,并且如果它仍然hover则检查每X毫秒,如果是,则运行另一个函数。

编辑:这对我有用 : http : //jsfiddle.net/z8yaB/

对于简单接口中的大多数用途,您可以使用jquery的hoverfunction,只需将鼠标hover在某处就可以存储在布尔值中。 然后你可以使用一个简单的setInterval循环来检查这个状态的每个ms。 您还可以在第一条评论中看到链接副本中的答案(编辑:现在在此处的其他答案中)。

但也有一些情况,特别是当hover生成错误警报时,当鼠标和对象之间移动物体时。

对于这些情况,我创建了这个函数来检查当jquery调用我的处理程序时事件是否真的hover在元素上:

 var bubbling = {}; bubbling.eventIsOver = function(event, o) { if ((!o) || o==null) return false; var pos = o.offset(); var ex = event.pageX; var ey = event.pageY; if ( ex>=pos.left && ex<=pos.left+o.width() && ey>=pos.top && ey<=pos.top+o.height() ) { return true; } return false; }; 

当我收到mouseout事件时,我使用此函数检查鼠标是否真的离开了:

  $('body').delegate(' myselector ', 'mouseenter', function(event) { bubbling.bubbleTarget = $(this); // store somewhere that the mouse is in the object }).live('mouseout', function(event) { if (bubbling.eventIsOver(event, bubbling.bubbleTarget)) return; // store somewhere that the mouse leaved the object }); 

您可以使用variablename = setInterval(...)在鼠标hover时重复启动函数,并使用clearInterval(variablename)在mouseout上停止它。

http://jsfiddle.net/XE8sK/

 var marker; $('#test').on('mouseover', function() { marker = setInterval(function() { $('#siren').show().fadeOut('slow'); }, 500); }).on('mouseout', function() { clearInterval(marker); });​ 

jQuery有hover()方法,它为您提供了开箱即用的function:

 $('.myiv').hover( function () { // the element is hovered over... do stuff }, function () { // the element is no longer hovered... do stuff } ); 

如果元素仍然hover,则检查每x毫秒,并响应以下内容:

 var x = 10; // number of milliseconds var intervalId; $('.myiv').hover( function () { // the element is hovered over... do stuff intervalId = window.setInterval(someFunction, x); }, function () { // the element is no longer hovered... do stuff window.clearInterval(intervalId); } ); 

演示 – http://jsfiddle.net/z8yaB/

 var interval = 0; $('.myiv').hover( function () { interval = setInterval(function(){ console.log('still hovering'); },1000); }, function () { clearInterval(interval); } );