小编典典
我的建议是尽可能避免这样做。而是使用类来分配颜色值,然后可以使用该类而不是颜色值来查找元素。
据我所知,没有可用于查询 特定
样式值的选择器(即使在CSS3中也是如此),这意味着循环遍历所有元素(或者看起来可以将其限制为具有style属性的所有元素)并看着element.style.color财产。现在,问题是,即使您`color:
333;在style属性中编写代码,不同的浏览器也会以不同的方式将其回显给您。可能是#333,可能是#333333,rgb(51, 51,
51)甚至是rgba(51, 51, 51, 0)`。
因此,总的来说,这确实是一个非常尴尬的练习。
既然您说过这是针对Chrome扩展程序的,那么您可能不必担心多种格式,尽管我会随意介绍一下我们曾经在野外看到的格式,以防Chrome更改格式(也许与其他已知的浏览器保持一致)。
但例如:
(function() {
// Get all elements that have a style attribute
var elms = document.querySelectorAll("*[style]");
// Loop through them
Array.prototype.forEach.call(elms, function(elm) {
// Get the color value
var clr = elm.style.color || "";
// Remove all whitespace, make it all lower case
clr = clr.replace(/\s/g, "").toLowerCase();
// Switch on the possible values we know of
switch (clr) {
case "#333":
case "#333333":
case "rgb(51,51,51)": // <=== This is the one Chrome seems to use
case "rgba(51,51,51,0)":
elm.style.color = "#444";
break;
}
});
})();
活生生的例子用红为清楚起见 | 来源
-请注意,示例依赖于ES5功能和querySelectorAll,但是由于这是Chrome,因此我知道它们已经存在。
请注意,以上内容假定是内联样式,因为您已讨论了该style属性。如果您指的是 计算 样式,那么它就无济于事,只能遍历该页面上的 所有
元素,调用getComputedStyle。除此之外,以上适用。
最后的注意:如果您确实要使用样式属性,而该属性仅包含值color: #333而不是value
color:#333或color:#333333;or color: #333; font-weight:
bold或任何其他字符串,则querySelectorAll可以处理:`querySelectorAll(‘*[style=”color:
333”]’)`。但这将是 非常 脆弱的。
从下面的评论看来,您必须遍历 每个 元素。如果是这样,我根本不会使用querySelectorAll,而是使用递归下降:
function walk(elm) {
var node;
// ...handle this element's `style` or `getComputedStyle`...
// Handle child elements
for (node = elm.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 1) { // 1 == Element
walk(node);
}
}
}
// Kick it off starting with the `body` element
walk(document.body);
这样,您就不会建立大型的,不必要的临时结构。这可能是遍历文档的整个DOM的最有效方法。
2020-05-16