Css 关键帧循环,完成多个动画元素上的动画迭代

Css keyframe loop, finish iteration of animation on element with multiple animations

我有一个循环播放的 css 关键帧动画。 animation-iteration-count: infinite 现在,当我单击一个按钮时,我希望动画完成当前循环然后停止。

this问题似乎相关,但animationiteration webkitAnimationIteration回调似乎不会在关键帧动画结束时调用,但更频繁。

EDIT: This turned out to almost be the correct solution, only that it can't handle multiple animations. For more info see my answer below.

This example 显示我的动画,悬停时我想尝试完成当前循环然后停止。这包括@Alex Gru 提出的答案,如果等待动画多次循环然后悬停你可以看到动画 jumps,这是行不通的。如果它没有循环完整的迭代并且我设置了 animation-iteration-count: 1 它会按预期工作。

这是针对您的用例的最小解决方案:

首先,当你想完成动画时,再添加一个class .stop

  $(".target").addClass("stop");

定义以下 css 样式,它完成当前循环并在之后停止动画。

.target.stop {
  -webkit-animation-iteration-count: 1;
  animation: none;
}

另见:

所以我发现了为什么它不起作用。毕竟还有一些关于我如何设法让它工作的额外信息,我将在这里解释。

这是我的错误因为还有另一个动画附加子元素:

<div id="a1"> <-- Main animation that should finish the loop
  <div id="a2"></div> <-- sub animation that should not be finished
</div>

这就是动画回调 where 比预期更频繁触发的原因。 但是:我发现我可以按动画名称过滤!

$("#a1").on('animationiteration webkitAnimationIteration', function(e) {
/* this triggers not only when animation of #a1 iterated but also if animation of #a2 iterated */
 let animation_name = e.originalEvent.animationName;
if(animation_name == "animation1name"){
 //This will only trigger if the correct animation iterated
}
});

我希望这个解决方案可以帮助那些试图处理应用于一个元素(或子元素)的多个循环动画的人

感谢所有帮助过的人! (我调整了问题标题以突出实际问题所在)