开发者

Weird behaviour in Chrome regarding document.styleSheets

开发者 https://www.devze.com 2023-04-11 10:39 出处:网络
I\'ve got this code... function disableSheets(){ console.log(document.styleSheets.length); var c = document.styleSheets.length;

I've got this code...

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);
}

When I run it in Firefox/Firebug it says:

3
StyleSheet
StyleSheet
StyleSheet
3

When I run it in Chrome/Developer Tools it says:

3
CSSStyleSheet
CSSStyleSheet
undefined
1

So my questions are:

  1. Why would it say there are开发者_如何学Go 3 stylesheets if the 3rd is undefined?
  2. How did I lose 2 stylesheets by the end of that loop?
  3. What happened to the 3rd sheet?

At the top of my HTML I have the 3 <link>s, linking the 3 stylesheets, and then immediately after that I call disableSheets().


Apparently, style sheets are removed from the document.styleSheets object (Chrome), when disabled.

Your code does actually read the first and third styleSheet:

An overview:

  • 3 stylesheets: A, B, C
  • var c = document.styleSheets.length;
  • Loop, i=0
  • i=0, Select styleSheet[i] = StyleSheet A
    2 stylesheets left: B, C
  • Loop, i=1
  • i=1, Select styleSheet[i] = StyleSheet C
    1 stylesheet left: B
  • Loop, i=2
  • i=2, Select styleSheet[i] = undefined
  • Loop i<3 = break
  • Console.log(document.styleSheets.length) = 1 (Stylesheet B)

To get your code work, reverse the loop:

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

Note: Initialise i at c-1! JavaScript array-like objects' indices are zero-based.


After thinking about the -webkit- bug for a while, I found a solution for it:

Just assigning document.styleSheets[n] to a global variable before disabling it , then it remains in the StyleSheetList.


Setting disable=true on stylesheet removes it from document.styleSheets

It is a bug in Chrome, Safari

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

0

精彩评论

暂无评论...
验证码 换一张
取 消