即使在函数外部设置了 var,JS clearTimeout 也无法工作
我试图在悬停时显示预览,但如果我将鼠标移开,我希望不显示预览。目前,如果我快速将鼠标移过“.searchRecord”元素,它无论如何都会在 300 毫秒后显示,并且会“卡住”,因为在 setTimeout 函数完成之前调用了鼠标关闭函数。如果我让光标停留在元素上,直到预览显示一切正常。
我在函数外部设置了变量,就像我在其他地方读到的那样,但是,它不会重置。我有点难住了。
var timer;
$('.searchRecord').hover(function() {
$(this).children('.previewLoad').show();
var current = '#'+$(this).children('div').attr('id');
//slight delay before hover so they can select what they want
var timer = window.setTimeout(function(){
$(current).fadeIn('fast');
$(current).siblings('.previewLoad').hide();
}, 300);
}, function() {
window.clearTimeout(timer);
var current = '#'+$(this).children('div').attr('id');
previewTimeouter(current);
});
I am trying to get a preview to display on hover, but if I move my mouse off, I want the preview not to display. Currently, if I quickly move my mouse across the ".searchRecord" element it will display after 300ms anyway, and be "stuck" as the mouse off function was called before the setTimeout function could finish. if I let me cursor stay on the element until the preview displays everything works just fine.
I set the variable outside the function as I read elsewhere, however, it doesn't reset. I'm a bit stumped.
var timer;
$('.searchRecord').hover(function() {
$(this).children('.previewLoad').show();
var current = '#'+$(this).children('div').attr('id');
//slight delay before hover so they can select what they want
var timer = window.setTimeout(function(){
$(current).fadeIn('fast');
$(current).siblings('.previewLoad').hide();
}, 300);
}, function() {
window.clearTimeout(timer);
var current = '#'+$(this).children('div').attr('id');
previewTimeouter(current);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有重复的计时器声明。删除悬停回调中
vartimer
中的var
。you have duplicated timer declaration. remove the
var
invar timer
in the hover callback.您在悬停回调中再次使用
var timer
,该回调将其范围限定为该函数并隐藏父timer
变量。删除该内部
var
一切都会好起来的。You are using
var timer
again inside of the hover callback, which scopes it to that function and shadows the parenttimer
variable.Remove that internal
var
and all shall be well.