如何在浏览器中规范化CSS3 Transition功能?

时间:2011-02-16 23:33:29

标签: javascript css javascript-events css3 css-transitions

Webkit的转换结束事件称为webkitTransitionEnd,Firefox是transitionEnd,opera是oTransitionEnd。在纯JS中处理所有这些问题的好方法是什么?我应该做浏览器嗅探吗?或分别实施每一个?还有其他一些方法没有发生在我身上吗?

即:

//doing browser sniffing
var transitionend = (isSafari) ? "webkitTransitionEnd" : (isFirefox) ? "transitionEnd" : (isOpera) ? "oTransitionEnd";

element.addEventListener(transitionend, function(){
  //do whatever
},false);

// Assigning an event listener per browser
element.addEventListener("webkitTransitionEnd", fn);
element.addEventListener("oTransitionEnd", fn);
element.addEventListener("transitionEnd", fn);

function fn() {
   //do whatever
}

11 个答案:

答案 0 :(得分:163)

Modernizr中使用了一种改进的技术:

function transitionEndEventName () {
    var i,
        undefined,
        el = document.createElement('div'),
        transitions = {
            'transition':'transitionend',
            'OTransition':'otransitionend',  // oTransitionEnd in very old Opera
            'MozTransition':'transitionend',
            'WebkitTransition':'webkitTransitionEnd'
        };

    for (i in transitions) {
        if (transitions.hasOwnProperty(i) && el.style[i] !== undefined) {
            return transitions[i];
        }
    }

    //TODO: throw 'TransitionEnd event is not supported in this browser'; 
}

然后,只要您需要转换结束事件,就可以调用此函数:

var transitionEnd = transitionEndEventName();
element.addEventListener(transitionEnd, theFunctionToInvoke, false);

答案 1 :(得分:22)

根据Matijs评论,检测转换事件的最简单方法是使用库,在这种情况下使用jquery:

$("div").bind("webkitTransitionEnd.done oTransitionEnd.done otransitionend.done transitionend.done msTransitionEnd.done", function(){
  // Unlisten called events by namespace,
  // to prevent multiple event calls. (See comment)
  // By the way, .done can be anything you like ;)
  $(this).off('.done')
});

在无库的javascript中,它有点冗长:

element.addEventListener('webkitTransitionEnd', callfunction, false);
element.addEventListener('oTransitionEnd', callfunction, false);
element.addEventListener('transitionend', callfunction, false);
element.addEventListener('msTransitionEnd', callfunction, false);

function callfunction() {
   //do whatever
}

答案 2 :(得分:8)

<强>更新

以下是更简洁的方法,并不需要modernizr

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

可选地

var transEndEventNames = {
        'WebkitTransition': 'webkitTransitionEnd',
        'MozTransition': 'transitionend',
        'OTransition': 'oTransitionEnd otransitionend',
        'msTransition': 'MSTransitionEnd',
        'transition': 'transitionend'
    }, transitionEnd = transEndEventNames[Modernizr.prefixed('transition')];

这是基于Modernizr建议的代码,但是对于较新版本的Opera有额外的事件。

http://modernizr.com/docs/#prefixed

答案 3 :(得分:8)

如果您使用jQuery和Bootstrap $.support.transition.end将返回当前浏览器的正确事件。

它是defined in Bootstrap并在its animation callbacks中使用,尽管jQuery文档说不依赖于这些属性:

  

虽然下面记录了其中一些属性,但它们不需要很长的弃用/删除周期,并且一旦内部jQuery代码不再需要它们就可以删除它们。

     

http://api.jquery.com/jQuery.support/

答案 4 :(得分:6)

截至2015年,这个单行应该做的交易(IE 10 +,Chrome 1 +,Safari 3.2 +,FF 4+和Opera 12 +): -

var transEndEventName = ('WebkitTransition' in document.documentElement.style) ? 'webkitTransitionEnd' : 'transitionend'

附加事件监听器很简单: -

element.addEventListener(transEndEventName , theFunctionToInvoke);

答案 5 :(得分:1)

这是一种更清洁的方式

 function transitionEvent() {
      // Create a fake element
      var el = document.createElement("div");

      if(el.style.OTransition) return "oTransitionEnd";
      if(el.style.WebkitTransition) return "webkitTransitionEnd";
      return "transitionend";
    }

答案 6 :(得分:0)

第二个是要走的路。

,每个浏览器中只会触发其中一个事件,因此您可以设置所有这些事件

答案 7 :(得分:0)

我使用这样的代码(使用jQuery)

var vP = "";
var transitionEnd = "transitionend";
if ($.browser.webkit) {
    vP = "-webkit-";
    transitionEnd = "webkitTransitionEnd";
} else if ($.browser.msie) {
    vP = "-ms-";
} else if ($.browser.mozilla) {
    vP = "-moz-";
} else if ($.browser.opera) {
    vP = "-o-";
    transitionEnd = "otransitionend"; //oTransitionEnd for very old Opera
}

这让我可以通过指定与属性连接的vP来使用JS添加内容,如果它没有访问浏览器,则只使用标准。这些事件让我很容易绑定:

object.bind(transitionEnd,function(){
    callback();
});

答案 8 :(得分:0)

谷歌关闭确保您不必这样做。如果你有一个元素:

goog.events.listen(element, goog.events.EventType.TRANSITIONEND, function(event) {
  // ... your code here
});

查看goog.events.eventtype.js的来源,通过查看useragent来计算TRANSITIONEND:

// CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  TRANSITIONEND: goog.userAgent.WEBKIT ? 'webkitTransitionEnd' :
      (goog.userAgent.OPERA ? 'oTransitionEnd' : 'transitionend'),

答案 9 :(得分:0)

jquery覆盖:

(function ($) {
  var oldOn = $.fn.on;

  $.fn.on = function (types, selector, data, fn, /*INTERNAL*/ one) {
    if (types === 'transitionend') {
      types = 'transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd';
    }

    return oldOn.call(this, types, selector, data, fn, one);
  };
})(jQuery);

和用法如:

$('myDiv').on('transitionend', function() { ... });

答案 10 :(得分:0)

接受的答案是正确的,但是您不必一次又一次地重新创建该元素...

构建全局变量并添加函数:

(function(myLib, $, window, document, undefined){

/**
 * @summary
 * Returns the browser's supported animation end event type.
 * @desc
 * @see {@link https://jonsuh.com/blog/detect-the-end-of-css-animations-and-transitions-with-javascript/}
 * @function myLib.getAnimationEndType
 * @return {string} The animation end event type
 */
(function(){
   var type;

   myLib.getAnimationEndType = function(){
      if(!type)
         type = callback();
      return type;

      function callback(){
         var t,
             el = document.createElement("fakeelement");

         var animations = {
            "animation"      : "animationend",
            "OAnimation"     : "oAnimationEnd",
            "MozAnimation"   : "animationend",
            "WebkitAnimation": "webkitAnimationEnd"
         }

         for (t in animations){
            if (el.style[t] !== undefined){
               return animations[t];
            }
         }
      }
   }
}());

/**
 * @summary
 * Returns the browser's supported transition end event type.
 * @desc
 * @see {@link https://jonsuh.com/blog/detect-the-end-of-css-animations-and-transitions-with-javascript/}
 * @function myLib.getTransitionEndType
 * @return {string} The transition end event type
 */
(function(){
   var type;

   myLib.getTransitionEndType = function(){
      if(!type)
         type = callback();
      return type;

      function callback(){
         var t,
             el = document.createElement("fakeelement");

         var transitions = {
            "transition"      : "transitionend",
            "OTransition"     : "oTransitionEnd",
            "MozTransition"   : "transitionend",
            "WebkitTransition": "webkitTransitionEnd"
         }

         for (t in transitions){
            if (el.style[t] !== undefined){
               return transitions[t];
            }
         }
      }
   }
}());

}(window.myLib = window.myLib || {}, jQuery, window, document));