javascript - 即使在函数外部设置了 var,JS clearTimeout 也无法工作

标签 javascript jquery hover settimeout

我试图在悬停时显示预览,但如果我将鼠标移开,我希望不显示预览。目前,如果我快速将鼠标移过“.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/

相关文章:

javascript - Java 8 更新 91 问题

javascript - RequireJS 错误地从 URL 加载脚本

javascript - 从对象访问属性/方法 (javascript)

jquery - tinymce jquery 版本 vs jquery 插件

html - 更改 Hover.css 中动画的默认蓝色

javascript - 如何阅读 Immutable/React 文档页面的代码示例

jquery mobile弹出关闭按钮-如何关闭而不返回?

javascript - Jquery - 将类添加到列表,同时从以前单击的列表中删除

Jquery悬停添加类并在悬停时删除类

CSS3 过渡缓入和缓出框阴影