javascript - javascript如何跨瀏覽器標準化CSS3轉換功能?

  显示原文与译文双语对照的内容
54 4

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);

或者

//asigning an event listener per browser
element.addEventListener(webkitTransitionEnd, function(){callfunction()},false);
element.addEventListener(oTransitionEnd, function(){callfunction()},false);
element.addEventListener(transitionEnd, function(){callfunction()},false);
function callfunction() {
//do whatever
}
时间:原作者:0个回答

100 2

有一種技術在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);
原作者:
138 4

按照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
}
原作者:
140 5

更新

下面是一種更簡潔的方法,不需要 modernizr

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

Alternatively

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

原作者:
...