我愿意:
- 找到页面中所有元素的样式属性(例如:所有具有
color:#333;
的元素) - 为所有这些更改此属性(例如从
color:#333
更改为color:#444
)。
您对此有什么建议吗?
最佳答案
我的建议是尽可能避免这样做。相反,使用一个类来分配颜色值,然后您可以使用该类而不是颜色值来查找元素。
据我所知,没有选择器(甚至在 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
页面上的所有 元素之外别无他法。除此之外,上述内容均适用。
最后的注释:如果你真的想要一个样式属性,它的值恰好是 color: #333
而不是值 color:#333
或 color:# 333333;
或 颜色:#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);
这样你就不会 build 大型的、不必要的临时结构。这可能是遍历文档的整个 DOM 的最有效方法。
关于Javascript,CSS : Get element by style attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10767701/