2016-07-11 87 views
-2

我想檢測瀏覽器是否支持使用javascript的CSS屬性(特別是是否支持「filter」)?我該怎麼做?如何檢測瀏覽器是否支持使用javascript的css屬性?

我嘗試以下功能

supportsCssStyle: function (prop) { 
     var div = document.createElement('div'), 
      vendors = 'Khtml Ms O Moz Webkit'.split(' '), 
      len = vendors.length; 

     if (prop in div.style) return true; 

     prop = prop.replace(/^[a-z]/, function (val) { 
      return val.toUpperCase(); 
     }); 

     while (len--) { 
      if (vendors[len] + prop in div.style) { 
       // browser supports box-shadow. Do what you need. 
       // Or use a bang (!) to test if the browser doesn't. 
       return true; 
      } 
     } 
     return false; 
    }, 

,但它不工作

+2

聽起來像http://stackoverflow.com/questions/16189905/can-i-detect -whether-css-filter-effects-are-supported – nuway

+1

我不想使用Modernizr – Jasmine

+0

什麼不行?你的代碼適合我。 – Oriol

回答

3

正如奧里奧爾在評論中指出,我原來的答覆是錯的(但不知何故帶着3個upvotes)。這是一個更可靠的方法。

function supportsProperty(prop) { 
 
    var el = document.createElement("div"); 
 
    el.style.cssText = prop + ":initial"; 
 
    return el.style[prop] === "initial"; 
 
} 
 

 
function supportsValue(prop, value) { 
 
    var el = document.createElement("div"); 
 
    el.style.cssText = prop + ":" + value; 
 
    return el.style[prop] === value; 
 
} 
 

 
console.log("filter", supportsProperty("filter")); // true for me 
 
console.log("-ms-flex", supportsProperty("-ms-flex")); // false for me 
 
console.log("position:sticky", supportsValue("position", "sticky")); // true for me

+0

如何在計算樣式上使用'in'而不是在document.createElement('div').style'上使用它'? – Oriol

+0

@Oriol使用'.style'只會給你顯式設置元素的屬性。我想你可以嘗試在一個新的元素上設置屬性,並檢查它是否仍然適用,但我不確定所有瀏覽器如何處理。有些人可能會保留無效的財產,而另一些人(Firefox,至少)會拋出。 – Scott

+0

但是即使是沒有設置的屬性也被定義爲getters/setters。 OP在document.createElement('div')中的''filter''style'就像window.getComputedStyle(document.createElement(「div」))中的''filter' – Oriol

0

我知道這個問題是針對一個JS的解決方案,但因爲它是將要解決一個CSS問題,這可能是該@supports功能查詢是相當不錯的,現在支持的興趣。 ..except ...(驚喜!)Internet Explorer(邊緣支持它,雖然 - 完整列表在這裏:http://caniuse.com/#feat=css-featurequeries

相關問題