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

Ric*_*nns 0 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);
});
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 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'));
});
Run Code Online (Sandbox Code Playgroud)

更新:

顺便说一句.setTimeout回调中的这些行

e.preventDefault();
e.stopPropagation();
return false;
Run Code Online (Sandbox Code Playgroud)

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