一定时间后触发事件处理程序 [英] Fire an event handler after a certain amount of time

查看:55
本文介绍了一定时间后触发事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是这个

如果用户将元素悬停在元素上1秒钟以上,则该事件将发生,否则将不会发生.

If the user hover the element for more then 1 second, the event will happen, otherwise it should not.

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

I tried using the setTimeout() but it just delays the event and does not cancel it when the mouse leaves the element.

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

Are there any other ways to solve this problem?

$(".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);
});

推荐答案

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

You could listen to the mouseenter and mouseleave events and clear the timer in the mouseleave event handler:

$(".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回调

Btw. these lines in the setTimeout callback

e.preventDefault();
e.stopPropagation();
return false;

不会产生任何效果,因为在执行回调时,该事件已经冒出气泡并触发了默认操作(更不用说回调中的return false并不代表任何含义).您必须将它们直接放入事件处理程序中.

won't have any effect, as by the time the callback is executed, the event already bubbled up and triggered the default action (not to mention that return false from the callback does not mean anything). You have to put them directly into your event handler.

这篇关于一定时间后触发事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆