How do I detect a transition end without a JavaScript library?

前端 未结 3 368
礼貌的吻别
礼貌的吻别 2021-01-11 12:04

I\'d like to delete an object after it\'s done animating with a CSS transition, but I\'m not able to use a JavaScript library.

How do I detect when the animation is

3条回答
  •  被撕碎了的回忆
    2021-01-11 12:42

    I was unable to find a suitable 'transitionend' polyfill that met my requirements. So if you want something for hooking the transition end once, use this:

    (function() {
        var i,
            el = document.createElement('div'),
            transitions = {
                'transition':'transitionend',
                'OTransition':'otransitionend',  // oTransitionEnd in very old Opera
                'MozTransition':'transitionend',
                'WebkitTransition':'webkitTransitionEnd'
            };
    
        var transitionEnd = '';
        for (i in transitions) {
            if (transitions.hasOwnProperty(i) && el.style[i] !== undefined) {
                transitionEnd = transitions[i];
                break;
            }
        }
    
        Object.prototype.onTransitionEndOnce = function(callback) {
            if (transitionEnd === '') {
                callback();
                return this;
            }
            var transitionEndWrap = function(e) {
                callback(); 
                e.target.removeEventListener(e.type, transitionEndWrap);
            };
            this.addEventListener(transitionEnd, transitionEndWrap);
            return this;
        };
    }());
    

提交回复
热议问题