Javascript 使用jQuery按背景色查找div

Javascript 使用jQuery按背景色查找div,javascript,jquery,jquery-selectors,Javascript,Jquery,Jquery Selectors,我试图使用jQuery来查找既可见又有绿色背景的div的数量 (通常我只需向div添加一个类,将其设置为绿色,并在jQuery中检查该类,但在本例中,我实际上无法以任何方式更改页面本身的标记) 我当前的可视div部件的工作方式如下: if( // if there are more than one visible div $('div.progressContainer:visible').length > 0 ){ 我想在这里加入一些“背景色为绿色”的选择器 //

我试图使用jQuery来查找既可见又有绿色背景的div的数量

(通常我只需向div添加一个类,将其设置为绿色,并在jQuery中检查该类,但在本例中,我实际上无法以任何方式更改页面本身的标记)

我当前的可视div部件的工作方式如下:

if(  // if there are more than one visible div 
    $('div.progressContainer:visible').length > 0   
){
我想在这里加入一些“背景色为绿色”的选择器

// not legit javascript
if(  // if there are more than one visible div, and its color is green 
    $('div.progressContainer:visible[background-color:green]').length > 0   
){

可以这样做吗?

jQuery没有基于样式的选择器(除了
:visible
),所以您不能这样做

您可以改用
过滤器

$('div.progressContainer:visible').filter(function() {
    return $(this).css('background-color') === 'green';
})
请注意,它与背景色不匹配:#0F0

您可以执行以下操作:

if($('div.progressContainer:visible').css('background-color') == 'green'){
   //should equal true, if it's green
}
您可以使用以下方式微调所选内容:

$('div.progressContainer:visible').filter(function(){
   return $(this).css('background-color') == 'green';
});

如果你经常在多个位置使用这个,你也可以考虑编写你自己的自定义选择器()


然后您只需执行
$('div:visible:greenbg').stuff()

,正如@SLaks指出的,这与
#0f0
不匹配,但为您提供了一个包含所有这些检查的单一位置。
jQuery.expr[':'].greenbg = function(elem) {
        return jQuery(elem).css('background-color') === 'green';
};