Retorno de chamada na transição CSS
-
21-09-2019 - |
Pergunta
É possível obter uma notificação (como retorno de chamada) quando uma transição CSS foi concluída?
Solução
Eu sei que o safari implementa um webkittransitionend Retorno de chamada que você pode anexar diretamente ao elemento com a transição.
O exemplo deles (reformatado para várias linhas):
box.addEventListener(
'webkitTransitionEnd',
function( event ) {
alert( "Finished transition!" );
}, false );
Outras dicas
Sim, se essas coisas forem suportadas pelo navegador, um evento será acionado quando a transição é concluída. O evento real, no entanto, difere entre os navegadores:
- Navegadores de webkit (Chrome, Safari) Uso
webkitTransitionEnd
- Firefox usa
transitionend
- Ie9+ usa
msTransitionEnd
- Usos de ópera
oTransitionEnd
No entanto, você deve estar ciente de que webkitTransitionEnd
Nem sempre dispara! Isso me pegou várias vezes e parece ocorrer se a animação não tivesse efeito no elemento. Para contornar isso, faz sentido usar um tempo limite para demitir o manipulador de eventos no caso de não ter sido acionado como esperado. Um post sobre esse problema está disponível aqui: http://www.cuppadev.co.uk/the-trouble-with-css-ransitions/ <- 500 Erro do servidor interno
Com isso em mente, eu costumo usar este evento em um pedaço de código que se parece um pouco assim:
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: Para obter o nome da extremidade do evento de transição, você pode usar o método postado como a resposta em:Como normalizo as funções de transição do CSS3 entre os navegadores?.
Nota: Esta pergunta também está relacionada a: - Eventos de transição CSS3
Estou usando o código a seguir, é muito mais simples do que tentar detectar qual evento final específico um navegador usa.
$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd',
function() {
//do something
});
Alternativamente, se você usar o bootstrap, então você pode simplesmente fazer
$(".myClass").one($.support.transition.end,
function() {
//do something
});
Isso é porque eles incluem o seguinte em 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);
o plugin jQuery.Transit, um plug -in para transformações e transições CSS3, pode chamar suas animações CSS do script e fornecer um retorno de chamada.
Isso pode ser facilmente alcançado com o transitionend
Evento Consulte Documentação aquiUm exemplo simples:
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>