本文介绍了如何检查document.styleSheets [i]对象中是否存在属性cssRules?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查document.styleSheets [i]对象中是否存在属性cssRules?

How to check if property cssRules exists in document.styleSheets[i] object?

我发现我无法使用

if ( sheets[i].hasOwnProperty("cssRules") )
  because .cssRules is inherited property.

但是当我尝试使用

if( sheets[i].cssRules !== undefined )

>因此在调试器中(Firefox 48 Toolbox工具)出现异常:SecurityError。

so in debugger (Firefox 48 Toolbox tool) I got exception: SecurityError.

因此,代码失败。

var cssList = function(node) {
    var sheets = document.styleSheets, o = {};
    var sheet;
    for (var i in sheets) {
      if( sheets[i].cssRules !== undefined )
        sheet = sheets[i].cssRules;
      else
      if( sheets[i].rules !== undefined )
        sheet = sheets[i].rules;
      else
        continue;

      var rules = sheets[i].rules || sheets[i].cssRules;
    }
    return o;
}


推荐答案

您可以使用<$ c工作表[i] 中的$ c>'cssRules',以检测工作表[i] 是否具有 cssRules 属性。

You can use 'cssRules' in sheets[i] to detect if sheets[i] has a cssRules property.

但是,所有样式表都应具有 cssRules 属性,这样您将始终得到 true

However, all stylesheets should have a cssRules property, and then you will always get true.

您的问题是 cssRules 吸气剂出于安全原因引发错误。

Your problem is that the cssRules getter throws an error for security reasons.

我认为检测到该错误的唯一方法是使用 try 语句:

I think the only way to detect that is with a try statement:

try {
  var rules = sheets[i].cssRules;
} catch(err) {}
if(rules) // ...

这篇关于如何检查document.styleSheets [i]对象中是否存在属性cssRules?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 17:32