停止CSS动画,但让它的当前迭代完成 [英] Stopping a CSS animation but letting its current iteration finish
问题描述
我有以下HTML:
<div class="rotate"></div>
和以下CSS:
@-webkit-keyframes rotate {
to {
-webkit-transform: rotate(360deg);
}
}
.rotate {
width: 100px;
height: 100px;
background: red;
-webkit-animation-name: rotate;
-webkit-animation-duration: 5s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
}
我想知道是否有一种方法动画,但让它完成其当前的迭代(最好通过改变一个或几个CSS属性)。我已经尝试将 -webkit-animation-name
设置为空值,但是会导致元素以刺耳的方式跳回到其原始位置。我也尝试将 -webkit-animation-iteration-count
设置为 1
,但是做同样的事情。 p>
I want to know if there is a way (using JavaScript) to stop the animation but let it finish its current iteration (preferably by changing one or a few CSS properties). I have tried setting -webkit-animation-name
to have a blank value but that causes the element to jump back to its original position in a jarring fashion. I have also tried setting -webkit-animation-iteration-count
to 1
but that does the same thing.
推荐答案
在接收到 animationiteration
事件时停止动画。类似这样的东西(使用jQuery):
Stop the animation upon receiving an animationiteration
event. Something like this (using jQuery):
CSS
@-webkit-keyframes rotate {
to {
-webkit-transform: rotate(360deg);
}
}
.rotate {
width: 100px;
height: 100px;
background: red;
}
.rotate.anim {
-webkit-animation-name: rotate;
-webkit-animation-duration: 5s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
}
HTML
<div class="rotate anim">TEST</div>
<input id="stop" type="submit" value="stop it" />
JS
$("#stop").click(function() {
$(".rotate").one('animationiteration webkitAnimationIteration', function() {
$(this).removeClass("anim");
});
});
小提琴: http://jsfiddle.net/sSYYE/1/
请注意,我使用的是 .one
此处(不是 .on
),以便处理程序只运行一次。这样,动画可以稍后重新启动。
Note that I'm using .one
here (not .on
) so that the handler only runs once. That way, the animation can later be restarted.
这篇关于停止CSS动画,但让它的当前迭代完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!