作为一家公司,我们使用组件(Angular,Vue和React)来构建我们的应用程序,但是我们仍然拥有从遗留应用程序继承的大量全局样式.
例如:
.active {
background: red;
}
Run Code Online (Sandbox Code Playgroud)
将应用于页面上任何具有活动类的元素.
在浏览器中,有没有办法生成应用于页面的所有全局(即非命名空间)样式规则的列表,请记住这些规则可能存在于第三方库或其他杂项遗留内容中JavaScript的?
pse*_*ant 27
评估当前页面的CSS样式的唯一选择是使用document.styleSheets.它将返回一个CSSStyleSheets 列表.
您将需要关注document.styleSheets[n].cssRules,n等于您要评估哪个样式表.这将为您提供该样式表应用的所有样式的列表.每个样式表都有cssText一个selectorText属性.
如果你只想循环查找哪些样式是"非命名空间",你应该只使用这些selectorText属性.
下面是一些关于MDN的更多信息有关document.styleSheets.
这是一个例子(按"运行代码片段"查看结果):
var selectors = [];
var sheets = Array.from(document.styleSheets);
sheets.forEach(function(sheet) {
// Only Stylesheets from a same-origin domain expose `cssRules` for security reasons
try {
var rules = Array.from(sheet.cssRules);
rules.forEach(function(rule) {
selectors.push(rule.selectorText);
});
} catch (e) {
// Do something with external stylesheets if you want
}
});
console.log(selectors);Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Stylesheets</title>
<style>
.hello-world {
background: url(none.gif);
}
</style>
<!-- Won't work as it is not a same-original stylesheet -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<style>
.foo {
background: url(none.gif)
}
.bar {
background: url(none.gif);
}
</style>
</body>
</html>Run Code Online (Sandbox Code Playgroud)