jQuery 选择具有特定背景颜色的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/282198/
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-26 08:52:37  来源:igfitidea点击:

Selecting elements with a certain background color

jquerycssjquery-selectors

提问by Owen

I want to select a bunch of spans in a divwhose CSS contains a particular background color. How do I achieve this?

我想spandiv其 CSS 包含特定背景颜色的a 中选择一堆s 。我如何实现这一目标?

回答by Owen

if i understand the question correctly, the selector [attribute=value]will not workbecause <span>does not contain an attribute "background-color". you can test that out quickly to confirm it won't match anything:

如果我正确理解了这个问题,选择器[attribute=value]将无法工作,因为<span>它不包含“背景颜色”属性。您可以快速测试以确认它不会匹配任何内容:

$('#someDiv span[background-color]').size(); // returns 0

given:

给出:

.one, .two {
  background-color: black;
}

.three {
  background-color: red;
}

here's a snippet that will work:

这是一个可以工作的片段:

$('div#someDiv span').filter(function() {
    var match = 'rgb(0, 0, 0)'; // match background-color: black
    /*
        true = keep this element in our wrapped set
        false = remove this element from our wrapped set
                                                         */
    return ( $(this).css('background-color') == match );

}).css('background-color', 'green'); // change background color of all black spans
.one, .two {
  background-color: black;
}

.three {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<div id="someDiv">
    <span class="one">test one</span>
    <span class="two">test two</span>
    <span class="three">test three</span>
</div>

回答by okoman

Use the attribute selector [attribute=value] to look for a certain attribute value.

使用属性选择器 [attribute=value] 查找某个属性值。

#id_of_the_div span[background-color=rgb(255,255,255)]