防止jQuery函数重复两次效果?

时间:2011-07-11 10:09:04

标签: javascript jquery

我正在做这样的事情: 当用户 mouseenter DIV1时,DIV2将淡入,当用户 mouseout DIV1时,DIV2将 fadeOut

但是有些奇怪的事情正在发生,当你快速进出DIV1时,DIV2的FADEIN和OUT效果会重复你的徘徊总数。

例如: 我很快就在DIV1里进出了10次,DIV2会继续FADE IN和OUT 10次,虽然我的鼠标没有徘徊它。

我希望人们明白我在说什么。

CODE:

$('div1').bind('mouseenter', function() {
   $('div2').fadeIn(600);
});
$('div1').bind('mouseout', function() {
   $('div2').fadeOut(600);
});

谢谢你,祝你有个愉快的一天。

4 个答案:

答案 0 :(得分:6)

mouseout事件上使用.stop(true,true)来停止所有现有动画

这是工作小提琴http://jsfiddle.net/XkmFy/

答案 1 :(得分:0)

您可以在开始新动画时停止现有动画,而不是将其叠加:

$('div1').bind('mouseenter', function() {
   $('div2').stop().fadeIn(600);
});
$('div1').bind('mouseout', function() {
   $('div2').stop().fadeOut(600);
});

答案 2 :(得分:0)

您需要.stop,它会停止当前动画,以便动画队列不会被延迟动画填满:http://jsfiddle.net/pQQ2G/

$('#div1').bind('mouseenter', function() {
   $('#div2').stop().fadeIn(600);
});
$('#div1').bind('mouseout', function() {
   $('#div2').stop().fadeOut(600);
});

另外,你应该使用#div1div1选择div1个元素,而我认为你有div个元素。

答案 3 :(得分:0)

使用此

$('div1').bind('mouseenter', function() {
   $('div2').fadeIn(600).stop(true, true);
});
$('div1').bind('mouseout', function() {
   $('div2').fadeOut(600).stop(true, true);
});

希望有所帮助