【问题标题】:I cannot get all the cssRules for some pages我无法获得某些页面的所有 cssRules
【发布时间】:2015-10-26 02:25:39
【问题描述】:

我正在尝试使用 JavaScript 获取所有 CSS 规则。 在某些页面上我成功了,在某些页面上我没有成功。

例如,在 StackOverflow 中,我使用的是:

console.log(
document.styleSheets[1].href,'rules',
document.styleSheets[1].cssRules,'Should be css rules, and not null'
)

这是我得到的:

http://cdn.sstatic.net/stackoverflow/all.css?v=f7d3e9ff74be rules null Should be css rules, and not null

对于其他一些网站,它运行良好,但有时不行。

例如在 github.com 这是我得到的:

https://assets-cdn.github.com/assets/github2/index-87247f16e6450ef54cb0eda3f8f1484e33a3f18c7a7d3df1f76f67cba36a8d6d.css CSSRuleList {0: CSSStyleRule, 1: CSSStyleRule, 2: CSSStyleRule, 3: CSSStyleRule, 4: CSSStyleRule, 5: CSSStyleRule, 6: CSSStyleRule, 7: CSSStyleRule, 8: CSSStyleRule, 9: CSSStyleRule, 10: CSSStyleRule, 11: CSSStyleRule, 12: CSSStyleRule, 13: CSSStyleRule, 14: CSSStyleRule, 15: CSSStyleRule, 16: CSSStyleRule, 17: CSSStyleRule, 18: CSSStyleRule, 19: CSSStyleRule, 20: CSSStyleRule, 21: CSSStyleRule, 22: 

我能做什么?

  1. 我想可能是因为内容类型。但不是。它总是文本/css
  2. 我认为可能是因为 CORS 问题,但我没有发现这是问题所在。

【问题讨论】:

  • 您确定这不是 CORS 问题吗?见stackoverflow.com/questions/5678040/…
  • 不是CORS问题,看了这些问题,我明白其他域是不可能的(即使允许访问控制)
  • 你为什么不认为它是 CORS? cdn.sstatic.netstackoverflow.com 不是同一个域,因此您无法访问样式。
  • 这不是 CORS。你期待什么输出?您是否期望 null 不为空?您尝试获取href 的元素没有href,所以它是null

标签: javascript css


【解决方案1】:

document.styleSheets contains<style type="text/css"></style> 以及 <link rel="stylesheet" type="text/css" href="style.css"> 所以你不会从第一个获得 href。我会检查这些样式是否也不是空白的,以防它们没有 cssRules。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2012-09-20
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    相关资源
    最近更新 更多