我想知道为什么我的脚本可以在 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
Same Domain Stylesheet
关于javascript - 未捕获的 DOMException : Failed to read the 'cssRules' property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993633/