这不是一个简单的任务,因为你需要考虑到其他可能的颜色格式代表相同的值,例如:
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
而且,浏览器不以一致的方式行事。例如,即使在CSS中使用了十六进制值,Firefox和Chrome始终会返回rgb()字符串,但IE会返回已定义的CSS值。
如果你想确保你的目标正确的颜色,你应该把它转换成一个共同的格式,然后进行比较。
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","");
}
});
}
注:我toHex
功能不会做的唯一的事情是要考虑到3位十六进制颜色格式,所以你应该稍微修改它。