使用Javascript检测CSS功能

nic*_*ckf 5 javascript css browser

是否可以使用Javascript检测CSS支持?

例如,是否可以检测浏览器是否支持这样的属性选择器?

input[type='text'] { }
Run Code Online (Sandbox Code Playgroud)

Mar*_*son 5

Modernizr旨在检测浏览器功能,并且很可能在这种情况下提供帮助. http://www.modernizr.com/


Tom*_*lak 2

document.querySelectorAll("input[type='text']")
Run Code Online (Sandbox Code Playgroud)

但对于旧版浏览器来说,这自然是失败的。

除此之外,您可以使用该style属性来检查某个 CSS 属性是否已应用。

input[type='text'] {
  background-repeat: no-repeat; /* or any other irrelevant, non-default value */
}
Run Code Online (Sandbox Code Playgroud)

if (myInputElem.style.backgroundRepeat == "no-repeat") {
  // selector is supported
}
Run Code Online (Sandbox Code Playgroud)

  • 任何支持 qSA 的东西都支持 `[attr]` 选择器 (3认同)