Richiamata su transizione CSS
-
21-09-2019 - |
Domanda
E 'possibile ottenere una notifica (come callback) quando una transizione CSS è stato completato?
Soluzione
So che Safari implementa un webkitTransitionEnd callback che è possibile allegare direttamente all'elemento con la transizione.
Il loro esempio (riformattato per più linee):
box.addEventListener(
'webkitTransitionEnd',
function( event ) {
alert( "Finished transition!" );
}, false );
Altri suggerimenti
Sì, se queste cose sono supportate dal browser, quindi viene attivato un evento quando la transizione completa. L'evento reale però, si differenzia tra i browser:
- browser Webkit (Chrome, Safari) utilizzano
webkitTransitionEnd
- Firefox utilizza
transitionend
- IE9 + utilizza
msTransitionEnd
- Opera utilizza
oTransitionEnd
Tuttavia si deve essere consapevoli che non sempre webkitTransitionEnd
fuoco! Questo mi ha catturato un certo numero di volte, e sembra che si verifichi se l'animazione non avrebbe alcun effetto sull'elemento. Per ovviare a questo, ha senso utilizzare un timeout per sparare il gestore di eventi nel caso in cui non è stato attivato come previsto. Un post sul blog su questo problema è disponibile qui: http: // www. cuppadev.co.uk/the-trouble-with-css-transitions/ <- 500 Internal Server Error
Con questo in mente, tendo a utilizzare questo evento in un pezzo di codice che sembra un po 'come questo:
var transitionEndEventName = "XXX"; //figure out, e.g. "webkitTransitionEnd"..
var elemToAnimate = ... //the thing you want to animate..
var done = false;
var transitionEnded = function(){
done = true;
//do your transition finished stuff..
elemToAnimate.removeEventListener(transitionEndEventName,
transitionEnded, false);
};
elemToAnimate.addEventListener(transitionEndEventName,
transitionEnded, false);
//animation triggering code here..
//ensure tidy up if event doesn't fire..
setTimeout(function(){
if(!done){
console.log("timeout needed to call transition ended..");
transitionEnded();
}
}, XXX); //note: XXX should be the time required for the
//animation to complete plus a grace period (e.g. 10ms)
Nota: per ottenere il nome fine dell'evento di transizione è possibile utilizzare il metodo registrato come la risposta in: Come faccio a normalizzare le funzioni di transizione CSS3 tutti i browser? .
Nota: questa domanda è anche legato a: - eventi CSS3 transizione
Sto usando il seguente codice, è molto più semplice che cercare di rilevare quale evento finale specifica utilizza un browser.
$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd',
function() {
//do something
});
In alternativa, se si utilizza bootstrap allora si può semplicemente fare
$(".myClass").one($.support.transition.end,
function() {
//do something
});
Questa è becuase essi includono quanto segue in bootstrap.js
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'transition' : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
})
}(jQuery);
Il jQuery.transit plug , un plugin per le trasformazioni e transizioni CSS3, può chiamare le animazioni CSS dallo script e vi darò un callback.
Questo può essere facilmente raggiunto con l'evento transitionend
consultare la documentazione qui
Un semplice esempio:
document.getElementById("button").addEventListener("transitionend", myEndFunction);
function myEndFunction() {
this.innerHTML = "Transition event ended";
}
#button {transition: top 2s; position: relative; top: 0;}
<button id="button" onclick="this.style.top = '55px';">Click me to start animation</button>