javascript - 未捕获的 DOMException : Failed to read the 'cssRules' property

标签 javascript google-chrome

我想知道为什么我的脚本可以在 firefox 上运行,但不能在 google chrome 上运行

JS:

var _timelineWidth = (Number.parseInt(document.styleSheets[0].cssRules[16].style.width) / 100) * document.body.clientWidth;

CSS:

#timeline {
  position: relative;
  top: 15px;
  left: 12.5%;
  height: 5px;
  background: #aaa;
  border-radius: 2.5px;
  cursor: pointer;
}

这是来自 chrome 的错误代码

Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules

最佳答案

在最新的 Chrome 中,CORS 安全规则也适用于样式表(类似于 Iframe 规则)。

您可以加载和呈现它们,但不能通过 javascript 访问内容(如果从跨域加载)。

如果您的 CSS 样式表来自与 HTML 相同的域/或包含在相同的 HTML 文件中,您将能够访问 document.styleSheets[elem].cssRules 否则它会抛出错误

Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules

Cross Domain Stylesheet

Cross Domain Stylesheet

Same Domain Stylesheet

Same Domain Stylesheet

关于javascript - 未捕获的 DOMException : Failed to read the 'cssRules' property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993633/

相关文章:

javascript - 元素拒绝淡出或淡入

javascript - Leaflet:自动将簇/或 Spiderfy 的颜色更改为簇中选定的标记。

javascript - 在网站上可视化图表

node.js - Chrome net::ERR_HTTP2_PROTOCOL_ERROR 200 重新连接后

javascript - 用于结束 chrome 选项卡进程的键盘快捷方式

面向 Cordova 的应用程序 POST cookie session 信息或传递给默认浏览器

javascript - 使用 JQuery 替换一页上的多个 HTML 实例

javascript - 三.颜色 : Unknown color #002dff (warning/error)

javascript - 如何知道点击事件是否是假冒的?

javascript - 如何确定 Chrome 扩展程序是否位于内容脚本的弹出窗口中?