作为一家公司,我们使用组件(Angular、Vue 和 React)来构建我们的应用程序,但我们仍然有大量从遗留应用程序继承的全局样式。
例如:
.active {
background: red;
}
将应用于页面上任何位置具有事件类的任何元素。
有没有办法在浏览器中生成适用于页面的所有全局(即非命名空间)样式规则的列表,请记住这些规则可能存在于第三方库中,或者其他杂项遗留 JavaScript?
最佳答案
评估当前页面的 CSS 样式的唯一选择是使用 document.styleSheets
。它将返回 CSSStyleSheet
的列表。
您需要关注 document.styleSheets[n].cssRules
,其中 n
等于您要评估的样式表。这将为您提供该样式表应用的所有样式的列表。每个样式表都有一个 cssText
和一个 selectorText
属性。
如果您只是想循环查找哪些样式是“非命名空间”的,您应该只使用 selectorText
属性。
这是一些 more information on 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);
<!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>
关于javascript - 有没有办法找到适用于网页的所有全局样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47412570/