javascript - 如何获取 CSS 样式的类
问题描述
我使用以下代码获取元素的所有 css 样式:
style = window.getComputedStyle(dom, null)
到目前为止,一切都很好。
我需要知道是否有样式以及是否有哪个类将 CSS 样式添加到此列表中。
例如,我们查看结果行
"background-image": "none",
我需要知道是否有一个应用这种样式的类,以及是否有一个名字有这个类的类,最好是来自哪个 CSS 文件。
如果有办法得到这个,信息最好的方法是什么?
解决方案
以下代码在我的本地主机中进行了测试。我用过 jQuery。
HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="style2.css">
<title>Document</title>
</head>
<body id="body">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
captureLinks();
});
function captureLinks() {
hrefs = [];
jQuery("link").each(function () {
hrefs.push(jQuery(this).attr('href'));
})
css_styles = {};
hrefs_count = 0;
jQuery.each(hrefs, function (index, href) {
jQuery.ajax({
url: href,
success: function (data) {
css_styles[href] = data.replace(/ /g, '').replace(/(\r\n\t|\n|\r\t)/gm, "");
},
complete: function () {
hrefs_count = hrefs_count + 1;
if (hrefs_count === hrefs.length)
allCssCaptured(css_styles);
}
})
})
}
function allCssCaptured(css_styles) {
css_reference = "background-image:none";
css_reference_remove_white_space = css_reference.replace(/ /g, ':');
css_sheet_reference = {};
jQuery.each(css_styles, function (filename, content) {
if (content.indexOf(css_reference_remove_white_space) !== -1) {
split_content = content.split(css_reference_remove_white_space);
left_of_css_reference = split_content[0];
for (var i = left_of_css_reference.length; i >= 0; i--) {
if (left_of_css_reference[i] === '{') {
j = i - 1;
for (j = i - 1; j >= 0; j--) {
if (left_of_css_reference[j] === ".") {
css_string = '';
for (var k = j; k < i; k++) {
css_string += left_of_css_reference[k];
}
css_sheet_reference[filename] = css_string;
}
}
}
}
}
});
console.log(css_sheet_reference)
}
</script>
</body>
</html>
样式表-2
.no-image {
color:yellow;
background-image: none;
}
样式表
.b{
background-color: blue;
}
.a{
background-color: #000;
}
.test{
background-color: red;
width: 100px;
height: 50px;
}
我得到了哪个样式表和哪个类的 console.log 结果。
谢谢你。
推荐阅读
- javascript - 使用 React 和 Enzyme 测试 Javascript 类属性
- python - 来人解释一下为什么这段代码对我不起作用?
- c# - Moq 通用存储库模式
- c# - ac# 控制台应用程序可以在 Windows 控件上获取反射信息吗?
- c# - 中继器不创建子控件
- android - 带有大 msg.obj 的处理程序可以抛出 TransactionTooLargeException 吗?
- azure-data-factory - 在 ADF 管道中使用 Teradata 作为源调整批量读取大小
- linux - 如何使用 vim 来检查某些可执行文件的 -h 参数或手册?
- angular - 在 Angular 中,当组件不是父/子时,如何将值从一个组件传递到另一个组件?
- python - Python pandas数据框检查一列的值是否在另一个列表中