jQuery的悬停和setTimeout / clearTimeOut [英] jquery hover and setTimeout / clearTimeOut
问题描述
我目前正在尝试使用子菜单做一个菜单。
这是我想要做的。
在悬停链接(#mylink)时,我想显示一个div(让我们称之为#submenu)在它下面。
在鼠标上留下这个链接想要在5秒后执行一个函数。
在5秒的间隔中,如果我将我的div(#submenu)我想清除超时。
所以这个div在5秒后不会消失。
这里是我的代码:
<$ p
$($#
$(#mylink)。hover(
function()
{
$('#submenu')。show();
},
function()
{
var timer = setTimeout(function(){$(' (
$);
$(#submenu)。hover(
function()
{
clearTimeout(timer);
},
function()
{
$('#submenu')。show();
$ div class =h2_lin>解决方案
SLaks有正确的答案,但要详细说明它,你可以在函数处理程序外面放置 var timer
。注意这个例子不会使 timer
一个全局变量 - 它只是扩大了它的范围,所以所有的处理程序都可以使用它。
$(document).ready(function(){
var timer;
$(#mylink)。hover(
function(){
$('#submenu')。show();
},function(){
timer = setTimeout(function(){$('#submenu')。hide();},5000);
}
);
$ b $(#submenu)。hover(
function(){
clearTimeout(timer);
},function(){
$ ('#submenu')。show();
}
);
}
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.
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.
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();
}
);
}
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.
$(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();
}
);
}
这篇关于jQuery的悬停和setTimeout / clearTimeOut的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!