Callback when CSS3 transition finishes

后端 未结 5 1843
野的像风
野的像风 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:27

    For transitions you can use the following to detect the end of a transition via jQuery:

    $("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
    

    Mozilla has an excellent reference:

    https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Detecting_the_start_and_completion_of_a_transition

    For animations it's very similar:

    $("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
    

    Note that you can pass all of the browser prefixed event strings into the bind() method simultaneously to support the event firing on all browsers that support it.

    Update:

    Per the comment left by Duck: you use jQuery's .one() method to ensure the handler only fires once. For example:

    $("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
    
    $("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
    

    Update 2:

    jQuery bind() method has been deprecated, and on() method is preferred as of jQuery 1.7. bind()

    You can also use off() method on the callback function to ensure it will be fired only once. Here is an example which is equivalent to using one() method:

    $("#someSelector")
    .on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",
     function(e){
        // do something here
        $(this).off(e);
     });
    

    References:

    • .off()

    • .one()

提交回复
热议问题