如何清除鼠标悬停时在每个函数内运行的 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();
});
关于jquery 在 mouseleave 上清除每个内部的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18951102/