开发者

Stop .hover animation when the mouse leaves in JQuery

I have something like:

$('.test').hover(
 function(){
  $(this).animate(...);
 }, function(){
  $(this).animate(...);
 }
);

But if the user's mouse leaves before the animation finishes, the animations continue. If I quickly hover and unhover the element quickly and repeatedly, the animations repeat several times afte开发者_开发知识库r the mouse left the element. How can I make the animations stop after the mouse left the element?


You're looking for stop():

$('.test').hover(
 function(){
  $(this).stop(true).animate(...);
 }, function(){
  $(this).stop(true).animate(...);
 }
);

There are two optional boolean parameters. The first is clearQueue. If set to false (or omitted), it is more like pausing the animation than stopping it. The next time you start an animation on that object it will finish the paused animation, and any other queued up animations, before continuing. In your case you want it to be true, which will tell it to actually stop the animation and clear any queued actions.

The second optional parameter is jumpToEnd. If false (or omitted), the animation is stopped in its tracks. If true, it will jump to the state the object is in at the end of the animation. You probably want to leave this one out, though it depends on what types of animations you're doing.

For example, suppose you are fading from 0% opacity to 100% opacity, and you are at 75% opacity when you call stop(), then you call a fade to 0% opacity. Without clearQueue, the object will continue fading to 100% and then fade back to 0%. With clearQueue, the object will stop fading at 75% then immediately start fading back to 0%. If jumpToEnd is true, the object would immediately change from 75% to 100% opacity before fading back to 0%.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜