目标是使用 jQuery 填充 css3 nth-child 伪类。因此,我需要解析 css 规则并使用 jQuery 将它们重新应用于不直接从 css 支持 nth-child 的旧浏览器。所以我写了一些代码,但我很确定类似的东西应该已经存在,例如在 github 上。可能有人已经遇到过这样的问题吗?这是我的代码:
// if ie7 or ie8
if (!$.support.leadingWhitespace) {
var aStyleSheetList = document.styleSheets,
aRules = [],
current = '',
aSelectors = [];
for (var i = 0; i < aStyleSheetList.length; i++) {
aRules = aStyleSheetList[i].cssRules || aStyleSheetList[i].rules;
for (var j = 0; j < aRules.length; j++) {
current = aRules[j];
if (current.selectorText && current.selectorText.indexOf('nth-child') !== -1) {
aSelectors.push([current.selectorText, current.cssText.substring(current.cssText.indexOf('{') + 1, current.cssText.indexOf('}'))]);
}
}
}
var jqCssObject = {},
declarations = [],
keyValuePair = [];
for (var k = 0; k < aSelectors.length; k++) {
declarations = aSelectors[k][1].split(';');
for (var m = 0; m < declarations.length; m++) {
keyValuePair = declarations[m].split(':');
jqCssObject[keyValuePair[0]] = keyValuePair[1];
}
$(aSelectors[k][0]).css(jqCssObject);
}
}