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

原作者:
...