给定一个 CSS 属性,例如
color: #fff;
我如何找到应用此属性的所有类名?
例如,
.hello {
color: #fff;
background: blue;
}
.world {
color: pink;
background: teal;
}
.white,
.classname {
color: #fff;
}
将返回 .hello
、.white
和 .classname
,因为它们都具有属性 color: #fff
.
最佳答案
可以遍历styleSheets,然后遍历rules..
这是一个例子..
它还包含一个转换颜色的实用函数,因为在样式表中 #fff 将是 rgb(255, 255, 255)..
function realColor (name) {
const d = document.createElement("div");
d.style.color = name;
d.style.display = "none";
document.body.appendChild(d);
const ret = window.getComputedStyle(d).color;
d.remove();
return ret;
}
const findcolor = realColor("#fff");
console.log("What selectors have a color of #fff?");
for (const s of document.styleSheets) {
for (const r of s.cssRules) {
if (r.style && r.style.color) {
if (r.style.color === findcolor) {
console.log(r.selectorText);
}
}
}
}
.hello {
color: #fff;
background: blue;
}
.world {
color: pink;
background: teal;
}
.white,
.classname {
color: #fff;
}
<span class="hello">hello</span>
<span class="world">world</span>
关于javascript - 获取某些 CSS 属性的所有类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51139575/