我的建议是尽可能避免这样做。相反,使用一个类来分配颜色值,然后您可以使用该类而不是颜色值来查找元素。
据我所知,没有可用于查询 特定 样式值的选择器(即使在 CSS3 中也没有),这意味着循环遍历所有元素(或者看起来像可以将其限制为具有style 属性的所有元素)并查看element.style.color 属性。现在,问题是,即使你在style 属性中写了color: #333;,不同的浏览器也会以不同的方式回显给你。可能是#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;
}
});
})();
Live example using red for clarity | source - 请注意,该示例依赖于 ES5 功能和 querySelectorAll,但由于这是 Chrome,我知道它们在那里。
请注意,以上假设为内联样式,因为您谈到了style 属性。如果您的意思是 computed 样式,那么除了在调用 getComputedStyle 的页面上循环遍历 all 元素之外别无他法。除此之外,以上适用。
最后说明:如果您的真正意思是样式属性的值恰好是 color: #333 而不是值 color:#333 或 color:#333333; 或 color: #333; font-weight: bold 或任何其他字符串,您的 querySelectorAll 可以处理:@987654341 @。但它会非常脆弱。
从您下面的评论中,听起来您必须遍历 每个 元素。如果是这样,我根本不会使用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 的最有效方式。