我有这个代码...
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
所以我的问题是:
- 如果第 3 个未定义,为什么会说有 3 个样式表?
- 我是如何在该循环结束时丢失 2 个样式表的?
- 第三张表怎么了?
在我的 HTML 顶部,我有 3 <link>
s,链接 3 个样式表,然后我立即调用 disableSheets()
.
最佳答案
显然,样式表已从 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<3
=break
-
Console.log(document.styleSheets.length)
=1
(样式表 B)
要使您的代码正常工作,请反转循环:
for(var i=c-1; i>=0; i--){
注意:初始化i
在 c-1
强>! JavaScript 类数组对象的索引是从零开始的。
关于javascript - Chrome 中关于 document.styleSheets 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7677377/