如何在jquery中停止以前的dom元素动画

How to stop previous dom element animation in jquery

本文关键字:dom 元素 动画 jquery      更新时间:2023-09-26

我正在尝试使用jquery来使用动画。当我将鼠标悬停在元素上时,它会增加高度,当mouseout时,会返回到原始高度。

问题是,当我将鼠标从一个元素移到另一个元素时,上一个元素的动画仍在执行。如何停止上一个元素的动画?

Fiddle代码:

http://jsfiddle.net/EVZVQ/

使用.stop():http://api.jquery.com/stop

$('.div_1').mouseover(function(){
    $(this).stop().animate({'height':'200px'},2000);
}).mouseout(function(){
    $(this).stop().animate({'height':'100px'},2000);
});

请注意,您可以链接事件绑定函数,而不是连续两次选择.div_1

下面是一个演示:http://jsfiddle.net/EVZVQ/1/

当对元素调用.stop()时,当前正在运行的动画(如有的话)立即停止。例如,如果一个元素当调用.stop()时,用.slideUp()隐藏,该元素现在将仍然显示,但将是其先前高度的一小部分。不调用回调函数。

来源:http://api.jquery.com/stop

更新

你可以像这样一次停止所有的div(但我不确定这是你想要的效果):

var $divs = $('.div_1');
$divs.mouseover(function(){
    $divs.stop().filter(this).animate({'height':'200px'},250);
}).mouseout(function(){
    $divs.stop().filter(this).animate({'height':'100px'},250);
});

下面是一个演示:http://jsfiddle.net/EVZVQ/2/

这样做效果更好。

$('.div_1').mouseover(function(){
    $(this).stop(true).animate({'height':'200px'},200);
});
$('.div_1').mouseout(function(){
    $(this).stop(true).animate({'height':'100px'},200);
});

http://jsfiddle.net/diode/EVZVQ/7/