我需要的是:
如果用户将元素悬停超过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);
});
答案 0 :(得分:6)
您可以收听mouseenter
和mouseleave
事件并清除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
并不意味着什么)。您必须将它们直接放入事件处理程序中。