jquery 在 mouseleave 上清除每个内部的 setTimeout

标签 jquery settimeout each

如何清除鼠标悬停时在每个函数内运行的 setTimeout 函数

这是简单的代码

var timer;

function Close() {
    clearTimeout(timer);
    $(child).css({left:0});
}

$(element).mouseover(function() {
    $(child).each(function(i) {
        var timer = setTimeout(function() {
                        $(child).eq('+i+').stop().animate({left:300});
                    }, 350 * (i + 1))
    });
})

$(element).mouseleave(function() {
    Close()
})

它工作正常,但问题是当鼠标在完成动画之前快速移动时,它们不会首先停止并返回到默认位置,因为 setTimeout 函数当然未完成。

最佳答案

试试这个方法:

function Close() {
    $(child).each(function() {
        window.clearTimeout($(this).data('timerId')); //clear it here
    }).css({left:0});
}

$(element).mouseenter(function() {
    $(child).each(function(i) {
          var timer =  window.setTimeout(function() {
                        $(child).eq(i).stop().animate({left:300});
                    }, 350 * (i + 1));

          $(this).data('timerId', timer); //save timer id here
    });
})

$(element).mouseleave(function() {
     Close();
});

另请注意,mouseover 的配对事件是 mouseout 而不是 mouseleave(这是 mouseenter 的配对事件) )。

<强> Fiddle

这是另一个清除动画的版本(不确定您在寻找什么)

   function Close() {

        $child.each(function () {
            window.clearTimeout($(this).data('timerId')); //clear it here
        });

        $child.stop(true, true, true).css({left:0}); //clear the queues and reset the position
    }

$(element).mouseenter(function () {
    $child.each(function (i) {
        var timer = window.setTimeout(function () {
            $child.eq(i).stop().animate({
                left: '300px'
            });
        }, 350 * (i + 1));

        $(this).data('timerId', timer); //save timer id here
    });
})

$(element).mouseleave(function () {
    Close();
});

Fiddle

关于jquery 在 mouseleave 上清除每个内部的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18951102/

相关文章:

PHP 生成表中的 Javascript 函数仅适用于第 1 行

javascript - 一段时间后重复执行函数的好模式是什么?

javascript - 如何停止队列动画 jquery?

javascript - 等到变量等于

jQuery Ajax setTimeout JSON

jquery - 将索引附加到 href

jQuery 每个循环 - 使用变量

jquery - 查找值是否为 int 下拉框

javascript - 如何选择输入元素? (文本突出显示)

javascript - 如何使用 jQuery 使用 data-filters 属性检索 "Result One"?