jquery clear setTimeout在mouseleave上的每个内部

jquery clear setTimeout在mouseleave上的每个内部,jquery,settimeout,each,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() {

如何清除在鼠标上方的每个函数中运行的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()
})
它工作正常,但问题是当鼠标在完成动画之前快速移动时,它们不会先停止并返回到默认位置,因为设置超时功能当然未完成。

请尝试以下方法:

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
的配对)

下面是另一个清除动画的版本(不确定您要查找什么)


还添加了第二个版本。请尝试快速移动鼠标以理解我的意思
   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();
});