我试图在悬停时显示预览,但如果我将鼠标移开,我希望不显示预览。目前,如果我快速将鼠标移过“.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);
});
最佳答案
您有重复的计时器声明。删除悬停回调中 vartimer
中的 var
。
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
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);
});
关于javascript - 即使在函数外部设置了 var,JS clearTimeout 也无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7885200/