HTML代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<link rel="stylesheet" type="text/css" href="base.css" />
<style>
div{width: 200px; height: 150px; }
</style>
</head>
<body>
<div style="background-color: #f60;"></div>
<script type="text/javascript">
var link = document.querySelector("link");
console.log(link.sheet.cssRules);
</script>
</body>
</html>
外部样式表base.css的代码如下:
@charset "utf-8";
div{
margin: 20px auto;
border-radius: 5px;
box-shadow: 3px 3px 5px #999;
}
在chrome中,打开控制台,得到的结果如下:
而在FF浏览器中,就正常了。IE中,把cssRules改为rules也是可以的。所以,我想问问这是不是chrome的兼容性问题?
这个存在浏览器兼容性的问题。
最好不要直接通过cssRules操作样式,这个更偏向于底层,一次性大量操作css规则的时候使用。
IE>9以上,是使用cssRules,貌似IE对于rules也可以得到。
FF和Chrome主要是cssRules
对于IE8及其以下,需要通过document.styleSheets来操作。
所以,一般兼容性可以这样来处理:
var rules=link.sheet.cssRules||link.sheet.rules||document.styleSheets;
我记得我曾经在处理一个移动端转场的时候,用过这个,当时也没有处理IE的兼容性。