jquery 悬停和 setTimeout / clearTimeOut
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10299531/
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 hover and setTimeout / clearTimeOut
提问by Franck HAMEL
I'm currently trying to do a menu with submenu. Here is what i want to do.
我目前正在尝试做一个带有子菜单的菜单。这是我想要做的。
On hover a link (#mylink) i want to display a div (lets call it "#submenu") right under it. On mouse leave this link a want to execute a function after 5 second.
在悬停链接 (#mylink) 时,我想在它的正下方显示一个 div(我们称之为“#submenu”)。在鼠标离开此链接 5 秒后要执行一个功能。
In this interval of 5 seconds, if i hover my div (#submenu) i want to clearTimeout. So this div won't desapear after 5 seconds.
在这 5 秒的间隔内,如果我将鼠标悬停在 div (#submenu) 上,我想清除超时。所以这个 div 不会在 5 秒后消失。
Here is my code :
这是我的代码:
$(document).ready(function()
{
$("#mylink").hover(
function ()
{
$('#submenu').show();
},
function()
{
var timer = setTimeout(function(){$('#submenu').hide();}, 5000);
}
);
$("#submenu").hover(
function ()
{
clearTimeout(timer);
},
function()
{
$('#submenu').show();
}
);
}
回答by Jeff
SLaks has the right answer, but to elaborate on it, you would put var timer
outside the function handler. Note that this example doesn't make timer
a global variable - it just widens its scope so all handlers can use it.
SLaks 有正确的答案,但要详细说明,您可以将其放在var timer
函数处理程序之外。请注意,此示例并未创建timer
全局变量 - 它只是扩大了其范围,以便所有处理程序都可以使用它。
$(document).ready(function(){
var timer;
$("#mylink").hover(
function(){
$('#submenu').show();
}, function(){
timer = setTimeout(function(){$('#submenu').hide();}, 5000);
}
);
$("#submenu").hover(
function(){
clearTimeout(timer);
}, function(){
$('#submenu').show();
}
);
}
回答by SLaks
var timer
is a local variable.
It doesn't exist outside that handler.
var timer
是局部变量。
它不存在于该处理程序之外。
You need to make it a global variable.
您需要将其设为全局变量。
回答by Paula Bean
Here is how I would do it
这是我将如何做到的
var timer
$("#mylink").mouseenter(function(){clearTimeout(timer);$('#submenu').show()})
$("#mylink").mouseout(function(){timer = setTimeout(function(){$('#submenu').hide();}, 1000);})
回答by David Diez
If you put #submenu inside of #mylink you won't need a second event handler for #submenu and you would have something like this:
如果将#submenu 放在#mylink 中,您将不需要#submenu 的第二个事件处理程序,您将拥有如下内容:
var timer;
$(document).ready(function()
{
$('#mylink').hover(function()
{
clearTimeout(timer);
$('#submenu').show();
},function()
{
timer = setTimeout(function(){$('#submenu').hide();},5000);
});
}
By the way, you don't need jQuery for this. In plain js won't be so long to code.
顺便说一下,您不需要 jQuery。在普通的 js 中编码不会那么长。