问题
How can you detect which CSS animation just finished in JavaScript?
The ultimate need is to re-trigger a CSS animation. Due to our HTML hierarchy, we prefer not checking the element's class but instead taking action only when a particular animation ends. If you have a method that allows re-triggering an animation without removing/adding a class, please let us know.
Otherwise... our code:
page.find( '.button.letter' ).on( 'webkitAnimationEnd', function() {
$( this ).removeClass( 'tap_animation' );
console.log( 'Hi: ' + this.style.webkitAnimationName );
if ( !write_mode() ) {
do_write( this );
}
});
this.style.webkitAnimationName always returns the empty string.
Are we doing something wrong?
We need the code for WebKit browsers, specifically Mobile Safari.
Thanks!
回答1:
From jQuery you can access the originalEvent
object, and, from there, the animationName
property:
$('body').on('webkitAnimationEnd', function(e){
var animName = e.originalEvent.animationName;
console.log(animName);
});
(Webkit-only) JS Fiddle demo.
From there, simply use an if
to check what the animation name is/was (past-tense, I suppose, given that it ended).
The above updated, to give possibly a better illustration:
$('div').on('webkitAnimationEnd', function(e){
var animName = e.originalEvent.animationName;
if (animName == 'bgAnim') {
alert('the ' + animName + ' animation has finished');
}
});
(Webkit-only) JS Fiddle demo.
This demo uses the following HTML:
<div><span>text</span></div>
And CSS:
@-webkit-keyframes bgAnim {
0%, 100% {
color: #000;
background-color: #f00;
}
50% {
color: #fff;
background-color: #0f0;
}
}
@-webkit-keyframes fontSize {
0%, 100% {
font-size: 100%;
}
50% {
font-size: 300%;
}
}
div {
font-weight: bold;
-webkit-animation: bgAnim;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 2;
}
span {
font-size: 100%;
font-weight: bold;
-webkit-animation: fontSize;
-webkit-animation-duration: 4s;
-webkit-animation-iteration-count: 1;
}
回答2:
An event listener for webkitAnimationEnd should work. Something along the lines of:
$object.addEventListener('webkitAnimationEnd', function(){
console.log( 'End Detected' );
}, false);
来源:https://stackoverflow.com/questions/12498686/detect-which-css-animation-just-ended-in-javascript