Callback when CSS3 transition finishes

后端 未结 5 1887
野的像风
野的像风 2020-11-22 09:30

I\'d like to fade out an element (transitioning its opacity to 0) and then when finished remove the element from the DOM.

In jQuery this is straight forward since yo

5条回答
  •  耶瑟儿~
    2020-11-22 10:10

    For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

    var cssAnimate = function(cssClass, callback) {
        var self = this;
    
        // Checks if correct animation has ended
        var setAnimationListener = function() {
            self.one(
                "webkitAnimationEnd oanimationend msAnimationEnd animationend",
                function(e) {
                    if(
                        e.originalEvent.animationName == cssClass &&
                        e.target === e.currentTarget
                    ) {
                        callback();
                    } else {
                        setAnimationListener();
                    }
                }
            );
        }
    
        self.addClass(cssClass);
        setAnimationListener();
    }
    

    I used it kinda like this

    cssAnimate.call($("#something"), "fadeIn", function() {
        console.log("Animation is complete");
        // Remove animation class name?
    });
    

    Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

    And this seems handy: http://api.jqueryui.com/addClass/


    Update

    After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

提交回复
热议问题