如何清除在鼠标悬停时每个函数内运行的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函数未完成。
答案 0 :(得分:1)
尝试这种方式:
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 强> 的