Javascript、CSS:通过样式属性获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10767701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:50:37  来源:igfitidea点击:

Javascript, CSS: Get element by style attribute

javascriptcss

提问by slwr

I'd like to:

我想:

  1. Find a style attribute for all elements in the page (for instance: all elements that have color:#333;)
  2. Change this attribute for all of them (for instance from color:#333to color:#444).
  1. 查找页面中所有元素的样式属性(例如:所有具有 的元素color:#333;
  2. 为所有这些更改此属性(例如从color:#333color:#444)。

Do you have any suggestion on doing so?

你有什么建议吗?

回答by T.J. Crowder

My suggestion is avoid doing this if at all remotely possible. Instead, use a class to assign the color value, and then you can look up the elements using the class, rather than the color value.

我的建议是尽可能避免这样做。相反,使用类来分配颜色值,然后您可以使用类而不是颜色值查找元素。

As far as I'm aware, there's no selector (not even in CSS3) that you can use to query a specificstyle value, which means looping through all elements (or it looks like you can restrict it to all elements with a styleattribute) and looking at the element.style.colorproperty. Now, the thing is, even though you write color: #333;in your styleattribute, different browsers will echo it back to you in different ways. It might be #333, it might be #333333, it might be rgb(51, 51, 51), it might even be rgba(51, 51, 51, 0).

据我所知,没有可用于查询特定样式值的选择器(甚至在 CSS3 中也没有),这意味着循环遍历所有元素(或者看起来您可以将其限制为具有style属性的所有元素)并看着element.style.color物业。现在,问题是,即使您color: #333;style属性中写入,不同的浏览器也会以不同的方式将其回显给您。可能是#333,可能是#333333,可能是rgb(51, 51, 51),甚至可能是rgba(51, 51, 51, 0)

So on the whole, a very awkward exercise indeed.

所以总的来说,这确实是一个非常尴尬的练习。



Since you've said this is for a Chrome extension, you probably don't have to worry as much about multiple formats, although I'd throw in the ones that we've seen in the wild in case Chrome changes the format (perhaps to be consistent with some other browser, which has been known to happen).

既然您已经说过这是针对 Chrome 扩展程序的,那么您可能不必担心多种格式,尽管我会加入我们在野外看到的那些,以防 Chrome 更改格式(也许与其他一些浏览器保持一致,这已经是已知的)。

But for instance:

但例如:

(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- Note that the example relies on ES5features and querySelectorAll, but as this is Chrome, I know they're there.

为清晰起见使用红色的现场示例| - 请注意,该示例依赖于ES5功能和querySelectorAll,但由于这是 Chrome,我知道它们在那里。

Note that the above assumes inline style, because you talked about the styleattribute. If you mean computedstyle, then there's nothing for it but to loop through allelements on the page calling getComputedStyle. Other than that, the above applies.

请注意,上面假定内联样式,因为您谈到了style属性。如果您的意思是计算样式,那么除了遍历页面上的所有元素调用getComputedStyle. 除此之外,以上均适用。

Final note: If you really meant a style attribute with precisely the value color: #333and not the value color:#333or color:#333333;or color: #333; font-weight: boldor any other string, your querySelectorAllcould handle that: querySelectorAll('*[style="color: #333"]'). But it would be veryfragile.

最后说明:如果您真的是指具有精确值color: #333而不是值color:#333color:#333333;color: #333; font-weight: bold或任何其他字符串的样式属性,则querySelectorAll可以处理:querySelectorAll('*[style="color: #333"]')。但它会非常脆弱。



From your comment below, it sounds like you're having to go through everyelement. If so, I wouldn't use querySelectorAllat all, I'd use recursive descent:

从您下面的评论中,听起来您必须遍历每个元素。如果是这样,我根本不会使用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);

That way you don't build up large, unnecessary temporary structures. This is probably the most efficient way to walk the entire DOM of a document.

这样你就不会建造大型的、不必要的临时结构。这可能是遍历文档整个 DOM 的最有效方法。

回答by Daniele B

It's definitely more simple if you use jquery. In any case, the best would be to use classes and use the filter jquery methodto get the objects you want.

如果你使用jquery,那肯定更简单。在任何情况下,最好的方法是使用类并使用filter jquery 方法来获取您想要的对象。

But if you really want to get them you can do something like:

但如果你真的想得到它们,你可以这样做:

$(function () {
    $('p').filter(function () {
        return $(this).css('color') == '#333';
    }).css('color', '#444');
});

The above script get the elements with the desired css attribute and set a new css attribute (color #444).

上面的脚本获取具有所需 css 属性的元素并设置一个新的 css 属性(颜色 #444)。

回答by mrzmyr

It's as already said really hard / inefficient to query all elements by color.

正如已经说过的那样,按颜色查询所有元素非常困难/效率低下。

// refrence: http://stackoverflow.com/questions/5999209/jquery-how-to-get-the-background-color-code-of-an-element
var arr = [];

$('*').each(function (i, ele) {
   // is red => save
   if($(ele).css('backgroundColor') == ('rgb(0, 0, 255)')) arr.push(ele);
});

console.log(arr);

Here is an JSFiddle Example for it: http://jsfiddle.net/ddAg7/

这是一个 JSFiddle 示例:http: //jsfiddle.net/ddAg7/

My recommendation for this is: Don't do it!

我对此的建议是:不要这样做!

回答by verisimilitude

Something like

就像是

$('selector').each(function() {
    if($(this).attr('style').indexOf('font-weight') > -1) {
        alert('got my attribute');
    }
});

in the if statement you could replace it with a different css... Not sure.. haven't tried on all browsers though :)

在 if 语句中,你可以用不同的 css 替换它......不确定......不过还没有在所有浏览器上尝试过:)

回答by Napolux

You can't, if you don't add at least a specific CSS class to all this elements you want to track.

如果不向所有要跟踪的元素添加至少一个特定的 CSS 类,则不能。

Or better, you can with very poor performances by looping on all the elements of the DOM until you find what you're looking for. But please, don't think of doing this

或者更好的是,您可以通过循环访问 DOM 的所有元素直到找到您要查找的内容,从而降低性能。但是请不要考虑这样做