【问题标题】:Weird behaviour in Chrome regarding document.styleSheetsChrome 中关于 document.styleSheets 的奇怪行为
【发布时间】:2011-10-06 16:20:00
【问题描述】:

我有这个代码...

function disableSheets(){
  console.log(document.styleSheets.length);
    var c = document.styleSheets.length;
    for(var i=0;i<c;i++){
      console.log(document.styleSheets[i]);
        if(typeof document.styleSheets[i]!=='undefined' && document.styleSheets[i].href.indexOf('stylezone')!=-1){
          document.styleSheets[i].disabled=true; 
        }
    }
    console.log(document.styleSheets.length);
}

当我在 Firefox/Firebug 中运行它时,它会说:

3
StyleSheet
StyleSheet
StyleSheet
3

当我在 Chrome/开发者工具中运行它时,它会说:

3
CSSStyleSheet
CSSStyleSheet
undefined
1

所以我的问题是:

  1. 如果第 3 个样式表未定义,为什么会说有 3 个样式表?
  2. 我是如何在循环结束时丢失 2 个样式表的?
  3. 第三张纸怎么了?

在我的 HTML 顶部有 3 个 &lt;link&gt;s,链接 3 个样式表,然后立即调用 disableSheets()

【问题讨论】:

    标签: javascript css google-chrome stylesheet


    【解决方案1】:

    显然,样式表在禁用时会从 document.styleSheets 对象 (Chrome) 中删除。

    您的代码确实读取了第一个和第三个样式表:

    概述:

    • 3 个样式表:A、B、C
    • var c = document.styleSheets.length;
    • 循环,i=0
    • i=0,选择styleSheet[i] = StyleSheet A
      剩下 2 个样式表:B、C
    • 循环,i=1
    • i=1,选择styleSheet[i] = StyleSheet C
      剩下 1 个样式表:B
    • 循环,i=2
    • i=2,选择styleSheet[i] = undefined
    • 循环 i&lt;3 = break
    • Console.log(document.styleSheets.length) = 1(样式表 B)

    要使您的代码正常工作,请反转循环:

     for(var i=c-1; i>=0; i--){
    

    注意:在 c-1 处初始化 i! JavaScript 类数组对象的索引是从零开始的。

    【讨论】:

    • 哦..现在说得通了。它仍然存在问题,因为我想稍后重新启用某些样式表,但现在我知道问题出在哪里,我可以解决它。谢谢!
    • 一个简单的解决方法是遍历所有 &lt;link&gt; (rel=* stylesheet) 和 &lt;style&gt; 元素。
    【解决方案2】:

    想了一会儿-webkit-这个bug,我找到了解决办法:

    在禁用它之前将 document.styleSheets[n] 分配给一个全局变量,然后它会保留在 StyleSheetList 中。

    【讨论】:

      【解决方案3】:

      在样式表上设置 disable=true 会将其从 document.styleSheets 中删除

      这是 Chrome、Safari 中的一个错误

      http://code.google.com/p/chromium/issues/detail?id=88310

      【讨论】:

        猜你喜欢
        • 2016-05-13
        • 2014-08-02
        • 2015-05-08
        • 1970-01-01
        • 1970-01-01
        • 2018-08-28
        • 2016-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多