Webkit的过渡结束事件称为webkitTransitionEnd,Firefox为transitionEnd,歌剧为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 }
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);