Jquery .on("mouseenter") - 等待 2 秒然后执行操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9025128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery .on("mouseenter") - wait 2 seconds then do action
提问by supercoolville
I have a script that shows hidden text when you hover over a div. But I want it to be delayed 2 seconds, and if the user moves the mouse away before 2 seconds I want nothing to be shown.
我有一个脚本,当您将鼠标悬停在 div 上时,它会显示隐藏文本。但我希望它延迟 2 秒,如果用户在 2 秒之前将鼠标移开,我不希望显示任何内容。
How do I do this?
我该怎么做呢?
What I have:http://jsfiddle.net/ZhrJT/
我有什么:http : //jsfiddle.net/ZhrJT/
-
——
HTML:
HTML:
<body>
<div>hover this</div>
<p class="hidden">unhidden!!</p>
</body>
JS:
JS:
$("body").on("mouseenter", "div", function(){
$("p").removeClass("hidden");
}).on("mouseleave", "div", function(){
$("p").addClass("hidden");
});
CSS:
CSS:
div {
background-color:red;
height:100px;
}
p.hidden {
display:none;
}
p {
background-color:yellow;
height:100px;
}
回答by Jasper
var timer;
$("body").on("mouseenter", "div", function(){
timer = setTimeout(function () {
$("p").removeClass("hidden");
}, 2000);
}).on("mouseleave", "div", function(){
clearTimeout(timer);
$("p").addClass("hidden");
});
There ya go, it's that easy. Just set a timeout that will hide the element when it runs and cancel the timeout if the user mouseleave
s the element.
就这样,就这么简单。只需设置一个超时,它会在元素运行时隐藏该元素,如果用户mouseleave
是该元素,则取消超时。
回答by Rocket Hazmat
Use setTimeout
/clearTimeout
. Something like this:
使用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");
});