.test
{
color:Red;
width: 100px;
}
var r = document.styleSheets[index].rules;
r[0].selectorText => Here we get ".test";
现在我想访问数组中的所有 .test 属性(在本例中为颜色和宽度)及其值(在本例中为 Red & 100px)。我该怎么做?
你想要 CSSStyleRule 的.cssText
。(您可以通过此页面上的console.log(document.styleSheets[2])
找到它,并在Chrome或Firebug的控制台中浏览项目。
另请注意,虽然.rules
在某些浏览器中工作,但 DOM 级别 2 CSS 绑定是.cssRules
。
编辑:如果需要访问单个样式,请使用 .style
属性。同样,您可以查看这是否使用了开发人员控制台。
var sheet = document.styleSheets[2];
var rules = sheet.cssRules[1];
console.log( rules ); // Lots of properties
console.log( Object.keys(rules) );
// ["parentRule", "cssText", "type", "selectorText", "style", "parentStyleSheet"]
console.log( rules.style.display ); // "none"
如果只想查看此规则中应用的样式,则必须循环访问 .style
集合的属性(包括未显式设置的属性)并检查空值,否则需要自己分析 cssText。
jQuery使这变得容易。
$('.test').each(function(){
var curColor = $(this).css('color');
// etc
});