开发者

Read all CSS selectors using jQuery

What is the best way to read all CSS selectors from my CSS $("head > style:eq(0)").h开发者_如何学运维tml(); ?


It varies across browsers. jQuery doesn't help you here, because inspecting the stylesheet data is a quite an unusual thing to want to do, and older/niche browsers can't do it at all. Are you sure you need to inspect stylesheets? What are you aiming to do?

var sheet= document.styleSheets[0];
var rules= 'cssRules' in sheet? sheet.cssRules : sheet.rules;
for (var i= 0; i<rules.length; i++) {
    var rule= rules[i];
    var text= 'cssText' in rule? rule.cssText : rule.selectorText+' {'+rule.style.cssText+'}';
    alert(text);
}

cssRules and cssText are standard DOM Level 2 Style properties, rules and selectorText are for IE<9 compatibility. Note IE<9 will return recreated rules so you'll see eg. PADDING-BOTTOM: 0pt; PADDING-LEFT: 0pt; PADDING-RIGHT: 0pt; PADDING-TOP: 0pt if the original style you specified was padding: 0.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜