给定一个已加载(可能有多个)CSS 文件和内联样式的网页,通过使用:
<link rel="stylesheet" type="text/css" href="some_file.css" />
<style type="text/css"> /* some css rules */ </style>
<link rel="stylesheet" type="text/css" href="some_other_file.css" />
<style type="text/css"> /* some other css rules */ </style>
<!-- etc -->
如何编写一个函数(可能使用 jQuery)来提取所有有效的网络 CSS 规则?
最佳答案
我不确定你想用这个做什么,但这应该让你开始:
function getStyles() {
if(!document.styleSheets) return false; // return false if browser sucks
var rules = new Array();
for (var i=0; i < document.styleSheets.length; i++) {
var x = 0;
styleSheet = document.styleSheets[i];
if(styleSheet.cssText) { // if this is IE, get the rules directly
rules.push(styleSheet.cssText);
} else {
// otherwise get them individually
do {
cssRule = styleSheet.cssRules[x];
if(cssRule) rules.push(cssRule.cssText);
x++;
} while (cssRule);
}
}
return rules;
}
当您调用它时,它将返回所有规则的数组。在 Firefox、IE 中测试。
关于javascript - 如何使用 jQuery(或类似的)来提取所有的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/641221/