DIV CSS 佈局教程網

用 JS 判斷瀏覽器是否支援某個 CSS3 屬性
編輯:關於JavaScript     

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;
}

程式碼解析

流程分三步:

  1. 組出候選名稱。把四個常見前綴與原屬性名拼接,得到 webkit-animation-play-state、Moz-animation-play-state 等,再加上無前綴的版本。
  2. 轉為駝峰。_toHumb 用正則 /-(\w)/g 找出「連字號加一個字」的組合,把該字轉大寫並去掉連字號。于是 animation-play-state 變成 animationPlayState。
  3. 逐一檢查。用 in 運算子在 document.documentElement.style 上檢查每個候選名稱是否存在,命中任一即回傳 true。

使用方式

alert(supportCss3('animation-play-state'));

傳入的是 CSS 中的原始寫法(連字號形式),轉換交給函式處理。

幾點改進建議

  • for...in 走訪陣列不嚴謹。若 Array.prototype 被擴充過,會撈到非預期的鍵。改用傳統 for 迴圈或 forEach 更安全。
  • 前綴清單可再精簡。現代瀏覽器中 -o- 前綴早已退場,實務上留 webkit 與 ms 通常就夠。
  • 回傳值可以更有用。與其只回 true/false,不如回傳「實際可用的屬性名」,這樣後續設定樣式時能直接拿去用:
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 之間。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved