0

我的页面上有类似的东西。

<div class="number_1" style="background-color:red"></div>
<div class="number_2" style="background-color:yellow"></div>
<div class="number_3"></div>
<div class="number_4"></div>
<div class="number_5" style="background-color:red"></div>

我无法通过添加背景颜色类来更改 HTML 代码!它必须从风格中红起来!

我需要这样的功能

for(var i=1; i<=5; i++){
    if($('.number_'+i).hasBackgroundColor('red')){
        //something
    }else{
        //somethign else
    }
}

.attr('style')==='background-color: red'似乎不起作用

.css('background-color')似乎也不起作用

4

6 回答 6

5

Here you get the background-color:

var backgroundColor = $('.number_'+i).css('background-color');

It will return something like "rgb(245, 180, 5)". Red color is "rgb(255,0,0)".

If you prefer getting hexa value, for example #ff0000 for red color, use such a function:

function hexc(colorval) {
    var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    delete(parts[0]);
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    color = '#' + parts.join('');
}
于 2013-07-10T11:52:38.853 回答
1

css('background-color') 在您的情况下以 rgb 返回颜色“rgb(255,0,0)”。

于 2013-07-10T11:53:13.513 回答
0

You can try using .css() method which return in rgb.

for (var i = 1; i <= 5; i++) {    
    if ($('.number_' + i).css("background-color") == "rgb(255, 0, 0)") { 
    //something    
    } else {
        //somethign else
    }
}

As T.J. Crowder mention, the above code works only in chrome and not in firefox or IEs.

Also try using RGB color parser in JavaScript

于 2013-07-10T11:52:54.650 回答
0

.attr('style')==='background-color: red' dont seem to work

一个空格会给出不同的结果:

$('<div style="background-color:red"></div>').attr('style') === 'background-color: red'

错误的

$('<div style="background-color:red"></div>').attr('style') === 'background-color:red'

真的

于 2013-07-10T11:57:48.393 回答
0
$(document).ready(function() {
$.each($('div') , function(index) {
alert($(this).attr('style'));
});
});

并且,然后在循环中添加您的其他逻辑/条件......

像这样的东西......

$(document).ready(function() {
$.each($('div') , function(index) {

style=$(this).attr('style');

if(style=='background-color: red;' || style=='background-color:red') {

    alert($(this).attr('class')+' is red!');

}

});
});
于 2013-07-10T11:57:27.407 回答
0

尝试这个,

for(var i=1; i<=5; i++){
    if($('.number_'+i).css('background-color')=='red'){ // or ==rgb(255,0,0)
        //something
    }else{
        //somethign else
    }
}
于 2013-07-10T11:54:01.860 回答