Jquery 在一定时间后触发事件处理程序
我需要的是: 如果用户将元素悬停超过1秒,则事件将发生,否则不应发生 我尝试使用Jquery 在一定时间后触发事件处理程序,jquery,Jquery,我需要的是: 如果用户将元素悬停超过1秒,则事件将发生,否则不应发生 我尝试使用setTimeout(),但它只是延迟事件,并且在鼠标离开元素时不会取消事件 还有其他办法解决这个问题吗 $(".optionCont").live('mouseover', function(e){ var $this = $(this); setTimeout(function(){ $(".dropMenuCont").stop(true,true).slideUp(200);
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);
});
您可以收听
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
没有任何意义)。您必须将它们直接放入事件处理程序。您可以收听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
没有任何意义)。您必须将它们直接放入事件处理程序。为什么不mouseover
和mouseout
?有什么区别吗?无论如何,我们将用这个来回答。@Shadow:mouseout
和mouseover
也将在您输入元素的后代时触发。在大多数情况下,你不想这样。谢谢,我不知道。因此jQuery.hover()
实际上使用的是mouseenter
和mouseleave
?@Shadow:Yes(在文档中;))。再看看这个:我现在很困惑。。这是否意味着jQuery有自己的IE实现,只执行mouseenter
和mouseleave
事件,使它们跨浏览器?为什么不执行mouseover
和mouseout
?有什么区别吗?无论如何,我们将用这个来回答。@Shadow:mouseout
和mouseover
也将在您输入元素的后代时触发。在大多数情况下,你不想这样。谢谢,我不知道。因此jQuery.hover()
实际上使用的是mouseenter
和mouseleave
?@Shadow:Yes(在文档中;))。再看看这个:我现在很困惑。。这是否意味着jQuery有自己的IE实现,只有mouseenter
和mouseleave
事件,使它们可以跨浏览器访问?