CSS3动画完成后是否有回调?

有没有办法实现一个回调函数的情况下,css3动画?在 Javascript 动画的情况下,这是可能的,但是没有找到任何方法在 css3中做到这一点。

我看到的一种方法是在动画持续时间之后执行回调,但是这并不能确保它总是在动画结束之后被调用。它将取决于浏览器 UI 队列。我想要一个更稳健的方法。有线索吗?

50533 次浏览

Yes, there is. The callback is an event, so you must add an event listener to catch it. This is an example with jQuery:

$("#sun").bind('oanimationend animationend webkitAnimationEnd', function() {
alert("fin")
});

Or pure js:

element.addEventListener("webkitAnimationEnd", callfunction,false);
element.addEventListener("animationend", callfunction,false);
element.addEventListener("oanimationend", callfunction,false);

Live demo: http://jsfiddle.net/W3y7h/

An easy way for you to do a callback that also handles your CSS3 transitions/browser compatibilities would be the jQuery Transit Plugin. Example:

//Pulsing, moving element
$("#element").click( function () {
$('#element').transition({ opacity: 0, x: '75%' }, function () { $(this).transition({ opacity: 1, x: '0%' }).trigger("click"); });
});

JS Fiddle Demo

If you created the animation with Javascript instead of CSS then you'll want to use the Animation API to set the callback for the animation's onfinish event.

animation = myAnimatedElement.animate([
{transform: 'translateX(0px)'},
{transform: 'translateX(-100px)'},
], 700);


animation.onfinish = (e) => {
// Do something after the animation finishes
};

Worth keeping in mind that if the animation is canceled, removed, or paused then the onfinish event does not fire. You may want to add listeners for those events as well depending on your needs.