【问题标题】:sheet.cssRules throws error on inner pages but works fine on homepagesheet.cssRules 在内页上抛出错误,但在主页上工作正常
【发布时间】:2020-03-06 09:30:18
【问题描述】:

我在我的 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

这是我网站的链接,

Homepage//here you will see no error in console

Inner Page//here you will see an error in console

根据我的研究,此错误是由跨域资源共享 (CORS) 引起的, 但为什么它在主页上工作?

【问题讨论】:

    标签: javascript css google-chrome dom


    【解决方案1】:

    毫无疑问,问题是由 CORS 引起的。我建议您console.log(document.styleSheets) 并查看元素的href 以检查在执行此操作document.styleSheets.length - 1 后将哪个样式表传递给您的addrule(),样式表的href 应该与您的域相同。

    【讨论】:

      【解决方案2】:

      如果没有在 sheet.cssRule 之前包含“../”,它将无法工作。继续计算内部文件的深度并添加“../”以完全等于该值。

      编写类似“../../../../sheet.cssRule”而不是“sheet.cssRule”的内容应该可以解决问题。

      【讨论】:

        【解决方案3】:

        我知道,当我们比较两个页面并尝试在脚本中使用 (;) 分号关闭 console.log 时,您的代码绝对没问题。

        console.log(sheet.cssRules);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-08-30
          • 1970-01-01
          • 1970-01-01
          • 2019-08-30
          • 1970-01-01
          • 1970-01-01
          • 2012-04-07
          相关资源
          最近更新 更多