使用下面的jQuery将获得元素背景颜色的RGB值:

$('#selector').css('backgroundColor');

有没有办法得到十六进制值而不是RGB?


当前回答

更新@ErickPetru的rgba兼容性:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

我更新了正则表达式,以匹配alpha值,如果定义,但不使用它。

其他回答

函数返回以十六进制表示的元素的背景色。

function getBgColorHex(elem){
    var color = elem.css('background-color')
    var hex;
    if(color.indexOf('#')>-1){
        //for IE
        hex = color;
    } else {
        var rgb = color.match(/\d+/g);
        hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
    }
    return hex;
}

使用的例子:

$('#div1').click(function(){
   alert(getBgColorHex($(this));
}

斯菲德尔

嗨,这是我的解决方案后,获得元素的颜色与Javascript

function rgb_hex(rgb_string_js){ //example: "rgb(102,54,255)"
  var new_rgb_list = rgb_string_js.replace("rgb(","").replace(")","").split(",");
  return ("#" + parseInt(new_rgb_list[0]).toString(16) + parseInt(new_rgb_list[1]).toString(16) + parseInt(new_rgb_list[2]).toString(16)); 
}

// c - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
let rgb2hex=c=>'#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``

// RGB -颜色STR,例如" RGB(12,233,43)",结果颜色十六进制,例如“# 0 ce92b” 让rgb2hex = c = > ' # ' + c.match (\ d + / g) . map (x = > (+ x) .toString (16) .padStart (2,0)) . join ' ' console.log (rgb2hex(“rgb(12233年,43”);

可读&& Reg-exp自由(无Reg-exp)

我创建了一个函数,它使用可读的基本函数,没有reg-exp。 该函数接受十六进制、rgb或rgba CSS格式的颜色,并返回十六进制表示。 编辑:有一个错误解析出rgba()格式,固定…

function getHexColor( color ){
    //if color is already in hex, just return it...
    if( color.indexOf('#') != -1 ) return color;
    
    //leave only "R,G,B" :
    color = color
                .replace("rgba", "") //must go BEFORE rgb replace
                .replace("rgb", "")
                .replace("(", "")
                .replace(")", "");
    color = color.split(","); // get Array["R","G","B"]
    
    // 0) add leading #
    // 1) add leading zero, so we get 0XY or 0X
    // 2) append leading zero with parsed out int value of R/G/B
    //    converted to HEX string representation
    // 3) slice out 2 last chars (get last 2 chars) => 
    //    => we get XY from 0XY and 0X stays the same
    return  "#"
            + ( '0' + parseInt(color[0], 10).toString(16) ).slice(-2)
            + ( '0' + parseInt(color[1], 10).toString(16) ).slice(-2)
            + ( '0' + parseInt(color[2], 10).toString(16) ).slice(-2);
}

由于问题是使用JQuery,下面是一个基于Daniel Elliott代码的JQuery插件:

$.fn.cssAsHex = function(colorProp) {

    var hexDigits = '0123456789abcdef';

    function hex(x) {
        return isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
    };

    // Convert RGB color to Hex format
    function rgb2hex(rgb) {
        var rgbRegex = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        return '#' + hex(rgbRegex[1]) + hex(rgbRegex[2]) + hex(rgbRegex[3]);
    };

    return rgb2hex(this.css(colorProp));
};

像这样使用它:

var hexBackgroundColor = $('#myElement').cssAsHex('background-color');