2012-01-26 37 views
13

我有一个脚本,显示隐藏的文字,当你将鼠标悬停在一个div。但我希望它延迟2秒,如果用户在2秒之前移开鼠标,我不想显示任何内容。jQuery的。对(“的mouseenter”) - 等待2秒,然后做动作

我该怎么做?

我有什么:http://jsfiddle.net/ZhrJT/

-

HTML:

<body> 
    <div>hover this</div> 
    <p class="hidden">unhidden!!</p> 
</body> 

JS:

$("body").on("mouseenter", "div", function(){ 
    $("p").removeClass("hidden"); 
}).on("mouseleave", "div", function(){ 
    $("p").addClass("hidden"); 
}); 

CSS:

div { 
    background-color:red; 
    height:100px; 
} 

p.hidden { 
    display:none; 
} 

p { 
    background-color:yellow; 
    height:100px; 
} 
+3

http://cherne.net/brian/resources/jquery.hoverIntent.html可能是你在找什么 – PeeHaa

回答

35
var timer; 
$("body").on("mouseenter", "div", function(){ 
    timer = setTimeout(function() { 
     $("p").removeClass("hidden"); 
    }, 2000); 
}).on("mouseleave", "div", function(){ 
    clearTimeout(timer); 
    $("p").addClass("hidden"); 
}); 

有雅去,就这么简单。只需设置超时在运行时,将隐藏的元素并取消超时如果用户mouseleave S中的元素。

+1

+1打我 –

+0

感谢!!!!!!!! !!!!!!!!!!!!!!! – supercoolville

+3

OMG你们是快...好工作...我的期待相同的:) –

5

使用setTimeout/clearTimeout。事情是这样的:

$("body").on("mouseenter", "div", function(){ 
    $(this).data('timeout', setTimeout(function(){ 
     $("p").removeClass("hidden"); 
    }, 2000)); 
}).on("mouseleave", "div", function(){ 
    clearTimeout($(this).data('timeout')); 
    $("p").addClass("hidden"); 
}); 
相关问题