javascript - sheet.cssRules 在内页上抛出错误,但在主页上工作正常
问题描述
我在我的 Wordpress 网站的自定义 javascript 中使用此功能。
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
console.log(sheet.cssRules)
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
这里的问题是上述功能在主页上运行良好,但是,
Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
在内页上抛出。
这是我网站的链接,
主页 //here you will see no error in console
内页 //here you will see an error in console
根据我的研究,此错误是由跨域资源共享 (CORS) 引起的,但为什么它在主页上起作用?
解决方案
毫无疑问,问题是由 CORS 引起的。我建议您在执行此操作后console.log(document.styleSheets)
查看href
元素以检查将哪个样式表传递给您的 addrule() document.styleSheets.length - 1
,样式表的 href 应该与您的域相同。
推荐阅读
- javascript - 使用 JavaScript 有效地应用样式(最佳实践?)
- javascript - Javascript/React:当兄弟组件/div 的高度发生变化时,window.scrollY 滚动时的像素数随机变化。为什么?
- django - 如何包含相关模型 Django
- python - 这个“值:06b”是什么意思?
- laravel - 如何获取要更新的日期的ID
- macos - 是否有在 Mac 上显示毫秒的视频播放器?
- angular - 究竟什么时候需要 compileComponents?
- pine-script - 自动缩放垂直线宽
- java - 当数据存储在堆栈中时,为什么我的函数没有返回堆栈(自制堆栈类)?
- android - 如何在 Android Studio For Android Noutgat 及以下的图像视图中放置图像