比如animationend就有几种:webkitAnimationEnd/oAnimationEnd/MSAnimationEnd/animationend,这样应该怎么写兼容的代码?或者是优雅降级的代码
比如requestAnimationFrame和cancelRequestAnimFrame可以这样写,但是animationend这样写不行...
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame || //Chromium
window.webkitRequestAnimationFrame || //Webkit
window.mozRequestAnimationFrame || //Mozilla Geko
window.oRequestAnimationFrame || //Opera Presto
window.msRequestAnimationFrame || //IE Trident?
function(callback, element){ //Fallback function
console.log("Fallback");
return window.setTimeout(callback, 1000/30);
}
})();
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
} )();
根据 dolymood 的方法,加上我wiki了一下,整理出一个可以判断浏览器前缀的方法,当然,使用limichange提到的Modernizr.prefixed也很方便。
var animEndEventNames = {
'webkit' : 'webkitAnimationEnd',
'o' : 'oAnimationEnd',
'ms' : 'MSAnimationEnd',
'animation' : 'animationend'
},
animEndEventName = animEndEventNames[prefix().lowercase]||animEndEventNames['animation'];
function prefix(){
var styles = getCompStyle(document.documentElement),
pre = (Array.prototype.slice.call(styles).join('')
.match(/-(moz|webkit|ms)-/) || ['', 'o']
)[1],
dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
return {
dom: dom,
lowercase: pre,
css: '-' + pre + '-',
js: pre[0].toUpperCase() + pre.substr(1)
};
};
function getCompStyle(elem,classes){
return (window.getComputedStyle?window.getComputedStyle(elem,classes||null):elem.currentStyle) || null;
}