CSS3 transition events

前端 未结 6 1346
情歌与酒
情歌与酒 2020-11-22 07:18

Are there any events fired by an element to check wether a css3 transition has started or end?

6条回答
  •  逝去的感伤
    2020-11-22 07:28

    Update

    All modern browsers now support the unprefixed event:

    element.addEventListener('transitionend', callback, false);

    https://caniuse.com/#feat=css-transitions


    I was using the approach given by Pete, however I have now started using the following

    $(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', 
    function() {
     //do something
    });
    

    Alternatively if you use bootstrap then you can simply do

    $(".myClass").one($.support.transition.end,
    function() {
     //do something
    });
    

    This is becuase they include the following 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 (  ._.)
      }
    
    
      $(function () {
        $.support.transition = transitionEnd()
      })
    
    }(jQuery);
    

    Note they also include an emulateTransitionEnd function which may be needed to ensure a callback always occurs.

      // 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
      }
    

    Be aware that sometimes this event doesn’t fire, usually in the case when properties don’t change or a paint isn’t triggered. To ensure we always get a callback, let’s set a timeout that’ll trigger the event manually.

    http://blog.alexmaccaw.com/css-transitions

提交回复
热议问题