如何跨浏览器标准化CSS3转换结束事件?
Webkit的转换结束事件称为webkitTransitionEnd,Firefox为TransitionEnd,Opera为oTransformtionEnd。用纯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
}
解决方案
Modelnizr中使用了一种改进的技术:
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);
相关文章