mouseover 事件上的clearTimeout 未从Mouseout 事件中清除setTimeout
我有一些代码将鼠标悬停事件和鼠标悬停事件添加到页面上的所有“a”标签。我希望鼠标移开时启动 5 秒计时器,然后调用函数。但是,如果触发新的鼠标悬停事件,它应该取消任何现有的计时器。我正在使用的代码如下。 setTimeout() 工作正常,但clearTimeout() 似乎没有引用正确的 timeoutID,即使我在全局声明它。有什么建议吗?
var timeoutID;
function addMouseoverEvent() {
$('a').each(function(index) {
$(this).mouseover(function() {
clearTimeout(timeoutID);
// do stuff
})
});
}
function addMouseoutEvent() {
$('a').each(function(index) {
$(this).mouseout(function() {
timeoutID = setTimeout(function() {
// do stuff
}, 5000);
})
});
}
$(window).load(function() {
addMouseoverEvent();
addMouseoutEvent();
});
我应该澄清的是,实际上应该只有一个活动计时器。这就是为什么我希望它是全球性的。如果发生鼠标悬停事件,则不应保留任何计时器。如果发生 mouseout 事件,则只有一个计时器应该处于活动状态 - 由最后一个 mouseout 事件触发的计时器。
I have some code that adds mouseover events and mouseout events to all 'a' tags on a page. I'd like it so that the mouseout starts a 5 second timer after which time it calls a function. However, if a new mouseover event fires, it should cancel any existing timers. The code I'm using follows. The setTimeout() is working fine, but it seems like the clearTimeout() isn't referencing the right timeoutID, even though I declared it globally. Any suggestions?
var timeoutID;
function addMouseoverEvent() {
$('a').each(function(index) {
$(this).mouseover(function() {
clearTimeout(timeoutID);
// do stuff
})
});
}
function addMouseoutEvent() {
$('a').each(function(index) {
$(this).mouseout(function() {
timeoutID = setTimeout(function() {
// do stuff
}, 5000);
})
});
}
$(window).load(function() {
addMouseoverEvent();
addMouseoutEvent();
});
I should clarify that there should really only ever be one active timer. That's why I wanted it to be global. If a mouseover event occurs no timers should remain. And if a mouseout event occurs only one timer should be active - the one triggered by the last mouseout event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这个问题已经得到解答,但我发现只需删除
.each()
调用即可使其看起来按预期工作。尝试这个 Fiddle 上的小悬停游戏。我很可能错过了一些东西——但悬停游戏似乎运行良好。
I know it's already been answered, but I found that simply removing the
.each()
call makes this appear to work as desired. Try the little hover game on this Fiddle.It's very possible I'm missing something -- but the hover game seems to work fine.
如果您的 timeoutId 是全局的,那么它会在
$('a').each()
的每次迭代中被覆盖。如果您使用 1.4,则最有可能使用delay
方法。或者您可以使用 $(this).data('timeoutId', setTimeout(youFunction)` 将 timeoutId 存储在元素上。If your timeoutId is globall then its going to get overwritten on each iteration of
$('a').each()
. If youre using 1.4 you can use thedelay
method most likely. or you could store the timeoutId on the element with $(this).data('timeoutId', setTimeout(youFunction)`.