CSS3 讓瀏覽器的表現力大幅提升,其中衝擊最大的莫過於動畫。但各家瀏覽器的支援進度不一,有些屬性甚至要加前綴才能用——例如 transition 的 animation-play-state,就長期只有部分瀏覽器支援。寫動畫庫或需要降級處理時,事先偵測能力是必要配備。
原理並不複雜:物件的 style 集合中,若存在某個屬性名稱,就代表瀏覽器認得它。難點在於名稱的形式——CSS 中寫 animation-play-state,在 JavaScript 中則要轉成駝峰的 animationPlayState;加上前綴後更複雜,例如 -webkit-animation-play-state 對應 webkitAnimationPlayState。
/**
* 判斷瀏覽器是否支援某一個 CSS3 屬性
* @param {String} 屬性名稱
* @return {Boolean} true/false
* @version 1.0
* @author ydr.me
*/
function supportCss3(style) {
var prefix = ['webkit', 'Moz', 'ms', 'o'],
i,
humpString = [],
htmlStyle = document.documentElement.style,
_toHumb = function (string) {
return string.replace(/-(\w)/g, function ($0, $1) {
return $1.toUpperCase();
});
};
for (i in prefix) humpString.push(_toHumb(prefix[i] + '-' + style));
humpString.push(_toHumb(style));
for (i in humpString)
if (humpString[i] in htmlStyle) return true;
return false;
}流程分三步:
/-(\w)/g 找出「連字號加一個字」的組合,把該字轉大寫並去掉連字號。于是 animation-play-state 變成 animationPlayState。alert(supportCss3('animation-play-state'));傳入的是 CSS 中的原始寫法(連字號形式),轉換交給函式處理。
function getSupportedProperty(style) {
var prefix = ['webkit', 'Moz', 'ms', 'o'],
htmlStyle = document.documentElement.style,
toHump = function (s) {
return s.replace(/-(\w)/g, function ($0, $1) {
return $1.toUpperCase();
});
},
candidates = [toHump(style)];
prefix.forEach(function(p){
candidates.push(toHump(p + '-' + style));
});
for (var i = 0; i < candidates.length; i++) {
if (candidates[i] in htmlStyle) return candidates[i];
}
return false;
}
var prop = getSupportedProperty('animation-play-state');
if (prop) {
document.getElementById("box").style[prop] = 'paused';
}今天處理這類問題有兩個更省事的做法:
一是 CSS.supports(),原生 API,語意直白:CSS.supports('animation-play-state', 'paused')。它支援所有現代瀏覽器,不必自己維護前綴清單。
二是讓 CSS 自己處理降級。寫入兩次即可,後者會覆蓋前者,不支援時自動忽略:
.box {
animation-play-state: paused;
-webkit-animation-play-state: paused;
}絕大多數情況下,第二種做法最乾淨——偵測能力與套用樣式一次完成,不必來回於 JS 與 CSS 之間。