Javascript 无法访问外部 CSSStyleSheet 中的规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49088507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:18:56  来源:igfitidea点击:

cannot access rules in external CSSStyleSheet

javascripthtmlcssgoogle-chrome

提问by nico.user

I am having trouble figuring out why .cssRulesand .ruleswon't work in my simplistic color generator project.

我无法弄清楚为什么.cssRules并且.rules在我的简单颜色生成器项目中不起作用。

I have a <link>element to link my external CSS file:

我有一个<link>元素来链接我的外部 CSS 文件:

<link href="ColorGenerator.css" type="text/css" rel="stylesheet">

And a <script>element to link my external JS file before the </html>element:

还有一个在<script>元素之前链接我的外部 JS 文件的</html>元素:

  <script src="ColorGenerator.js" type="text/javascript"></script>
</html>

I then have this in my CSS file:

然后我在我的 CSS 文件中有这个:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

#body {
  background: #E1E1F4;
}

And this on the JS file:

这在 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";
  }
};

But when I press space(e.keyCode == 32) nothing happens, so then I open the developer tools in Chrome and I get this error message:

但是当我按空格(e.keyCode == 32)时,什么也没有发生,所以我在 Chrome 中打开开发者工具,我收到了这个错误消息:

Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet': Cannot access rules at HTMLBodyElement.body.onkeydown

Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet': Cannot access rules at HTMLBodyElement.body.onkeydown

I'm not sure if Chrome just doesn't support it or if I have a failure in my code, eitherway I truly appreciate any help.

我不确定 Chrome 是否不支持它,或者我的代码是否失败,无论如何我真的很感激任何帮助。

回答by Brad Buchanan

As of Chrome 64, new CORS rules are enforced for stylesheets. You'll need to use a local development server to do local testing of functionality that depends on the CSS Object Model. For details, see Cannot access cssRules from local css file in Chrome.

从 Chrome 64 开始,对样式表强制执行新的 CORS 规则。您需要使用本地开发服务器对依赖于 CSS 对象模型的功能进行本地测试。有关详细信息,请参阅无法在 Chrome 中从本地 css 文件访问 cssRules