如何停止动画循环

时间:2021-03-09 20:23:18

The code below basicly animates a div back and forth. Then I want the animation to stop while hovering. It works if I remove this line: "$(".block").animate({left: '0px'}, 1, animate);" but then the div just animates once wich is not what I want. So how do keep the .stop() functionality but still get the animation to loop in infinity ?

下面的代码基本赋予了一个div元素。然后我希望动画在悬停的时候停止。如果我删除这一行,它是有效的:$(“.block”)。animate({左:'0px'}, 1, animate);“但是div仅仅在我不想要的时候才进行动画。那么,如何在保持.stop()功能的同时让动画无限循环呢?

$(function animate(){
$(".block").animate({left: '+=500px'}, 2000);
$(".block").animate({left: '0px'}, 1, animate);
});

$(".block").hover(function(){
$(".block").stop();
$(".block").animate({ width:"20%", height:"20%"}, 500 );
});

2 个解决方案

#1


11  

Updated

更新

Not sure if:

不确定:

$(".block").stop( true, true );

is what your looking for.

这就是你要找的。

The first true clears the queue and the last true jumps to the end of the animation queue, effectively ending the animation.

第一个true清除队列,最后一个true跳转到动画队列的末尾,有效地结束动画。

$(".block").stop( true );

This would clear the queue but NOT skip to the end.

这将清除队列,但不会跳转到最后。

#2


0  

I guess you can try writing another function on $(".block").mouseleave() and call animate inside it. This will be triggered when your mouse leaves the div. May be you also try the combination of mouseenter and mouseleave as well. In your case its working fine and stopping the animation as soon as your entering the div area, but there is no function to tell what to do when it comes out of it. I had a similar problem where I was fading an image on mouseover....it works well trying the above.

我想您可以尝试在$(.block).mouseleave()上编写另一个函数,并在其中调用animate。这将在您的鼠标离开div时被触发。您也可以尝试使用mouseenter和mouseleave的组合。在您的情况下,它可以正常工作,并在进入div区域后立即停止动画,但是没有函数可以告诉您当动画结束时该做什么。我有一个类似的问题,我消失一个图像mouseover ....尝试上述方法效果很好。

Hope this helps!

希望这可以帮助!

#1


11  

Updated

更新

Not sure if:

不确定:

$(".block").stop( true, true );

is what your looking for.

这就是你要找的。

The first true clears the queue and the last true jumps to the end of the animation queue, effectively ending the animation.

第一个true清除队列,最后一个true跳转到动画队列的末尾,有效地结束动画。

$(".block").stop( true );

This would clear the queue but NOT skip to the end.

这将清除队列,但不会跳转到最后。

#2


0  

I guess you can try writing another function on $(".block").mouseleave() and call animate inside it. This will be triggered when your mouse leaves the div. May be you also try the combination of mouseenter and mouseleave as well. In your case its working fine and stopping the animation as soon as your entering the div area, but there is no function to tell what to do when it comes out of it. I had a similar problem where I was fading an image on mouseover....it works well trying the above.

我想您可以尝试在$(.block).mouseleave()上编写另一个函数,并在其中调用animate。这将在您的鼠标离开div时被触发。您也可以尝试使用mouseenter和mouseleave的组合。在您的情况下,它可以正常工作,并在进入div区域后立即停止动画,但是没有函数可以告诉您当动画结束时该做什么。我有一个类似的问题,我消失一个图像mouseover ....尝试上述方法效果很好。

Hope this helps!

希望这可以帮助!