I wrote a small function that traverses the stylesheets on the document looking for the matched selector, then style.
There is one caveat, this will only work for style sheets defined with a style tag, or external sheets from the same domain.
If the sheet is known you can pass it in and save yourself from having to look in multiple sheets (faster and if you have colliding rules it's more exact).
I only tested on jsFiddle with some weak test cases, let me know if this works for you.
function getStyleRuleValue(style, selector, sheet) {
var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
for (var i = 0, l = sheets.length; i < l; i++) {
var sheet = sheets[i];
if( !sheet.cssRules ) { continue; }
for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
var rule = sheet.cssRules[j];
if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
return rule.style[style];
}
}
}
return null;
}
example usage:
var color = getStyleRuleValue('color', '.foo'); // searches all sheets for the first .foo rule and returns the set color style.
var color = getStyleRuleValue('color', '.foo', document.styleSheets[2]);
edit:
I neglected to take into consideration grouped rules. I changed the selector check to this:
if (rule.selectorText.split(',').indexOf(selector) !== -1) {
now it will check if any of the selectors in a grouped rules matches.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…