javascript 如何重新启动/重置 Jquery 动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25409023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:28:36  来源:igfitidea点击:

How to restart/reset Jquery animation

javascriptjqueryanimation

提问by Fede

How can i reset an animation in jquery ? For example:

如何在 jquery 中重置动画?例如:

CSS

CSS

.block {
    position:absolute;
    top: 0;
    left: 0;
}

JS:

JS:

$('.block').animate({
    left: 50,
    top: 50
});

If I do :

如果我做 :

$('.block').stop();

the animation will stop. But how can i clear the position, to start over ? from point 0,0.

动画将停止。但我怎样才能清除位置,重新开始?从点 0,0。

回答by Kami

When jQuery is animating an element, it adds the style related information in the styleattribute. If you need to reset the element to it's base style without the jQuery css, simply remove this attribute at the end of the animation - See .animate() on jQuery API.

当 jQuery 为元素设置动画时,它会在style属性中添加与样式相关的信息。如果您需要在没有 jQuery css 的情况下将元素重置为其基本样式,只需在动画结束时删除此属性 - 请参阅jQuery API 上的 .animate()

$('.block').animate({
    left: 50,
    top: 50
}, 'slow', function () { $(this).removeAttr('style'); });

The callback function will remove the styleattribute and reset the element at the end of the animation.

回调函数将style在动画结束时移除属性并重置元素。

回答by JF it

you're looking for jquery .finish

你正在寻找 jquery .finish

http://api.jquery.com/finish/

http://api.jquery.com/finish/

$('.block').finish().css('top', '0').css('left', '0');

回答by jfriend00

You can use .stop()like you are doing, but add an argument to it to also clear the queue and then reset your top and left positions using .css():

您可以.stop()像现在一样使用,但向它添加一个参数以清除队列,然后使用以下命令重置顶部和左侧位置.css()

$('.block').stop(true).css({top: 0, left: 0});


.finish()is also in this same category, but that puts all the animations at their final state which isn't something you want to do here. You just want to stop/clear the current animations (including any queued ones) and then reset the CSS properties back to your starting state.

.finish()也属于同一类别,但这会将所有动画置于最终状态,这不是您想要在这里做的事情。您只想停止/清除当前动画(包括任何排队的动画),然后将 CSS 属性重置回您的起始状态。

回答by ayed abboushi

to reset animation

重置动画

$('.block').removeAttr('style'); //
$('.block').animate({
    left: 50,
    top: 50
});