2010-05-23 44 views
5

为了我用户的完整性,我希望在选择器被半秒钟盘旋后运行'mouseover'事件,而不是只要他们盘旋它。如果元素已经被'鼠标悬停'了500ms,使用jQuery运行函数

我第一次尝试了一个setTimeout函数,但是它运行了很长时间,但是元素已经被徘徊了,我没有想太多。我也花了一天(开始和结束)搜索(并且玩Pacman)没有结果,除非我正在寻找错误的东西。

我想保留这个插件,如果可以的话,纯粹为了运行速度&可维护性。

$("#mySelector").mouseover(function(){ 
    // Run after 500ms 
    $(this).addClass("hasBeen500ms"); 
}); 

让我们看看我们是否可以破解这个,我知道它会有这么多的应用程序!

回答

14

无法显示了,如果鼠标已经脱离了由延迟时间到期,加上删除鼠标类:

$("#mySelector").mouseenter(function() { 
    var el = $(this); 
    var timeoutId = setTimeout(function() { 
    el.addClass("hasBeen500ms"); 
    }, 500); 
    el.mouseleave(function() { 
    clearTimeout(timeoutId); 
    el.removeClass("hasBeen500ms"); 
    }); 
}); 
​ 
+0

完美的作品!谢谢。 :) – PaulAdamDavis 2010-05-23 15:35:34

0

我试图建立在Web Logic's answer

创建一个变量来跟踪,如果鼠标仍然在说元素:

var isMouseOver=false; 

$("#mySelector").mouseover(function(){ 
    isMouseOver=true;//set variable to gtrue 
    setTimeout(function() { 
       if(isMouseOver){ 
         $(this).addClass("hasBeen500ms"); 
       } 
       }, 500); 
}); 

还设置mouseout回调,所以我们可以跟踪如果鼠标仍然存在500毫秒后。

$("#mySelector").mouseout(function(){ 
    isMouseOver=false;//set variable to false 
}); 

希望这个工程!

1

.delay()不起作用,因为.addClass()不是动画队列的一部分,所以相反我决定动画null(因为你不会在一个不可见的元素上盘旋而决定),然后运行添加悬停类在回调函数:

$('#mySelector').mouseenter(function(){ 
    $(this).animate({'visibility':'visible'},500,'swing',function(){ 
     $(this).addClass('hoverIntent'); 
    }) 
}); 

$('#mySelector').mouseleave(function(){ 
    $(this).removeClass('hoverIntent').stop().clearQueue(); 
}); 

在鼠标离开类被删除,并且动画队列停止的情况下,清除它的前500毫秒。如果您希望在取消停留前进行延迟,则可以在mouseleave中添加相同的功能。

1

另一种选择是取消超时如果一个人将鼠标移动了500毫秒之前已通过:

var timer; 

$('#mySelector').mouseover(function() { 
    timer = setTimeout(function() {$(this).addClass('hasBeen500ms');}, 500); 
}); 

$('#mySelector').mouseout(function() { 
    clearTimeout(timer); 
}); 
1

听起来像你可以使用hoverIntent插件。

+0

这是我的第一个回应,然后我读到他不想使用插件。 – mVChr 2010-05-23 15:43:52

+0

@mhr - 啊......我明显跳过那部分。无论如何,我仍然推荐它。这是一个已知的,记录和测试的代码片段。它只为jQuery对象添加了一个函数,并且它仅缩小了1.2kb。 – nickf 2010-05-23 23:00:17

+1

+1,但我想他想学鱼。 – mVChr 2010-05-24 00:05:46

0

如果你需要优化一点,你可以使用类似的东西。此代码适用于谷歌地图引脚,但您的想法

google.maps.event.addListener(marker, 'mouseover', function(){ 
    this.timeout = setTimeout(markerClick.bind(this, false), 500) 
    google.maps.event.addListener(this, 'mouseout', function(){ 
    if(this.timeout){ 
     clearTimeout(this.timeout) 
     delete this.timeout 
    } 
    google.maps.event.clearListeners(this, 'mouseout'); 
    }.bind(this)) 
}.bind(marker))