这是一个简单的问题示例:
<html>
<head>
<link rel='stylesheet' href='myStyle.css'>
<script>
window.onload=function(){
try{
alert(document.styleSheets[0]); // works
alert(document.styleSheets[0].cssRules); // doesn't even print undefined
}catch(e){alert(e)} // catch and alert the error
}
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
myStyle.css body{background-color:green;}
如果你使用脚本工作正常 <style></style>
解决方案:
1,作品文件时在线/本地主机
2.作品与其他浏览器(如IE浏览器,微软边缘,火狐)
3 铬--allow-文件访问从-文件
我无法弄清楚为什么.cssRules
而.rules
不会在我的简单的颜色生成项目.
我有一个<link>
链接我的外部CSS文件的元素:
<link href="ColorGenerator.css" type="text/css" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)
以及在<script>
元素之前链接我的外部JS文件的</html>
元素:
<script src="ColorGenerator.js" type="text/javascript"></script>
</html>
Run Code Online (Sandbox Code Playgroud)
然后我在我的CSS文件中有这个:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#body {
background: #E1E1F4;
}
Run Code Online (Sandbox Code Playgroud)
这个在JS文件上:
var mySheet = document.styleSheets[0];
var body = document.getElementById("body");
body.onkeydown = function(e){
if(e.keyCode == 32){
mySheet.rules[0].style.background = "#ffa500";
}
};
Run Code Online (Sandbox Code Playgroud)
但当我按空格(e.keyCode == 32
)没有任何反应时,那么我在Chrome中打开开发人员工具,我收到此错误消息:
Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet': Cannot access rules at HTMLBodyElement.body.onkeydown
我不确定Chrome是不支持它还是我的代码出现故障,无论如何我真的很感激任何帮助.