简体   繁体   English

如何将RGB颜色与RGBA颜色匹配

[英]How to match RGB color with RGBA color

I have a requirement that, I have to remove the background of the element if it matches with the specified color. 我有一个要求,如果元素与指定的颜色匹配,则必须删除它的背景。 This requirement is only for Chrome. 此要求仅适用于Chrome。 But if i use the below code 但是如果我使用下面的代码

function unhighlight() {
    $('*').each(function () {
        if($(this).css("background-color") == "rgb(0,128,128)"){
          $(this).css("background-color","");
        }
    });
}

But the above code is not working in Chrome, because the Chrome is trying to match with RGBA(). 但是上面的代码在Chrome中不起作用,因为Chrome试图与RGBA()匹配。
Is there any workaround for this..? 有什么解决方法吗? Please help me on this... 请帮我...

Works for me in Chrome. 在Chrome中为我工作。 I changed the selector to body * since I didn't want to capture the html and header tags etc. Also, make sure you're firing your function when the document is ready: 我将选择器更改为body *因为我不想捕获html和header标签等。此外,请确保在准备好文档时触发函数:

$(document).ready(function() { unhighlight(); });

function unhighlight() {
    $('body *').each(function () {
        if ($(this).css("background-color") == "rgb(255, 0, 0)"){
           $(this).css("background-color","");
        }
    });
}​

See here: http://jsfiddle.net/jfZBB/ 看到这里: http : //jsfiddle.net/jfZBB/

With a little investigating, it appears that elements which don't have an explicit background colour return: 经过一点调查,似乎没有明确背景颜色的元素会返回:

"rgba(0, 0, 0, 0)"

While coloured items return: 当有色物品返回时:

"rgb(171, 48, 76)"

This is not a trivial task, as you need to take into account other possible color formats which represent same value, ex: 这不是一件容易的事,因为您需要考虑代表相同值的其他可能的颜色格式,例如:

rgb(0,128,128)
rgba(0, 128, 128, 1)
#008080 //hey, why not, who said your color will be always defined in rgb? 
*#fc0 //different color to show alternative format, #ffcc00 == #fc0

Also, browsers don't behave in a consistent way. 另外,浏览器的行为也不是一致的。 For instance Firefox and Chrome always returns rgb() string even if hex value was used in CSS, however IE returns defined CSS value. 例如,即使CSS中使用了十六进制值,Firefox和Chrome始终返回rgb()字符串,但是IE返回已定义的CSS值。

If you want to ensure that you are targeting correct colour, you should convert it to a common format and then compare. 如果要确保目标颜色正确,则应将其转换为通用格式,然后进行比较。

function toHex(color)
{
    var m = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(color);
    return m ? '#' + (1 << 24 | m[1] << 16 | m[2] << 8 | m[3]).toString(16).substr(1) : color;
}

function unhighlight() {
    $('div').each(function () {
        if(toHex($(this).css("background-color")) == toHex("rgb(255,204,0)")){
          $(this).css("background-color","");
        }
    });
}

Note: The only thing my toHex function doesn't do is to take into account 3 digit hex color format, so you should slightly modify it. 注意: toHex函数唯一不做的事情就是考虑3位数的十六进制颜色格式,因此您应该对其稍加修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM