在一定时间后触发事件处理程序

时间:2011-08-22 13:46:32

标签: jquery

我需要的是:

如果用户将元素悬停超过1秒钟,则会发生该事件,否则不会发生。

我尝试使用setTimeout(),但它只会延迟事件,并且在鼠标离开元素时不会取消它。

还有其他方法可以解决这个问题吗?

$(".optionCont").live('mouseover', function(e){
    var $this = $(this);
    setTimeout(function(){
        $(".dropMenuCont").stop(true,true).slideUp(200);
        if($this.next().css("display") == "none"){
            $this.next().stop(true,true).slideDown(200);
        }else{
            $this.next().stop(true,true).slideUp(200);
        }
            e.preventDefault();
            e.stopPropagation();
            return false;

    }, 1000);
});

1 个答案:

答案 0 :(得分:6)

您可以收听mouseentermouseleave事件并清除mouseleave事件处理程序中的计时器:

$(".optionCont").live('mouseenter', function(e){
     var $this = $(this);
     var timer = setTimeout(function(){
          //...
     }, 1000);
     $this.data('timer', timer);
}).live('mouseleave', function(e) {
     clearTimeout($(this).data('timer'));
});

<强>更新

顺便说一下。 setTimeout回调

中的这些行
e.preventDefault();
e.stopPropagation();
return false;

不会产生任何影响,因为在执行回调时,事件已经冒泡并触发了默认操作(更不用说回调中的return false并不意味着什么)。您必须将它们直接放入事件处理程序中。