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

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

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


当前回答

var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

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

(源)

其他回答

var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

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

(源)

只是补充一下@Justin的回答。

应该是这样

var rgb = document.querySelector('#selector').style['background-color'];
return '#' + rgb.substr(4, rgb.indexOf(')') - 4).split(',').map((color) => String("0" + parseInt(color).toString(16)).slice(-2)).join('');

由于上面的解析int函数截断前导零,因此产生不正确的5或4个字母的颜色代码可能是…例如,对于rgb(216, 160, 10),它生成#d8a0a,而应该是#d8a00a。

谢谢

嗨,这是我的解决方案后,获得元素的颜色与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)); 
}

从bootstrap颜色选择器获取的颜色类

// Color object
var Color = function(val) {
    this.value = {
        h: 1,
        s: 1,
        b: 1,
        a: 1
    };
    this.setColor(val);
};

Color.prototype = {
    constructor: Color,

    //parse a string to HSB
    setColor: function(val){
        val = val.toLowerCase();
        var that = this;
        $.each( CPGlobal.stringParsers, function( i, parser ) {
            var match = parser.re.exec( val ),
            values = match && parser.parse( match ),
            space = parser.space||'rgba';
            if ( values ) {
                if (space === 'hsla') {
                    that.value = CPGlobal.RGBtoHSB.apply(null, CPGlobal.HSLtoRGB.apply(null, values));
                } else {
                    that.value = CPGlobal.RGBtoHSB.apply(null, values);
                }
                return false;
            }
        });
    },

    setHue: function(h) {
        this.value.h = 1- h;
    },

    setSaturation: function(s) {
        this.value.s = s;
    },

    setLightness: function(b) {
        this.value.b = 1- b;
    },

    setAlpha: function(a) {
        this.value.a = parseInt((1 - a)*100, 10)/100;
    },

    // HSBtoRGB from RaphaelJS
    // https://github.com/DmitryBaranovskiy/raphael/
    toRGB: function(h, s, b, a) {
        if (!h) {
            h = this.value.h;
            s = this.value.s;
            b = this.value.b;
        }
        h *= 360;
        var R, G, B, X, C;
        h = (h % 360) / 60;
        C = b * s;
        X = C * (1 - Math.abs(h % 2 - 1));
        R = G = B = b - C;

        h = ~~h;
        R += [C, X, 0, 0, X, C][h];
        G += [X, C, C, X, 0, 0][h];
        B += [0, 0, X, C, C, X][h];
        return {
            r: Math.round(R*255),
            g: Math.round(G*255),
            b: Math.round(B*255),
            a: a||this.value.a
        };
    },

    toHex: function(h, s, b, a){
        var rgb = this.toRGB(h, s, b, a);
        return '#'+((1 << 24) | (parseInt(rgb.r) << 16) | (parseInt(rgb.g) << 8) | parseInt(rgb.b)).toString(16).substr(1);
    },

    toHSL: function(h, s, b, a){
        if (!h) {
            h = this.value.h;
            s = this.value.s;
            b = this.value.b;
        }
        var H = h,
        L = (2 - s) * b,
        S = s * b;
        if (L > 0 && L <= 1) {
            S /= L;
        } else {
            S /= 2 - L;
        }
        L /= 2;
        if (S > 1) {
            S = 1;
        }
        return {
            h: H,
            s: S,
            l: L,
            a: a||this.value.a
        };
    }
};

如何使用

var color = new Color("RGB(0,5,5)");
color.toHex()

博士TL;

使用这个干净的单行函数,同时支持rgb和rgba:

const rgba2hex = (rgba) => `#${rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)$/).slice(1).map((n, i) => (i === 3 ? Math.round(parseFloat(n) * 255) : parseFloat(n)).toString(16).padStart(2, '0').replace('NaN', '')).join('')}`

2021年更新答案

从我最初回答这个问题到现在已经过去了很久。然后很酷的ECMAScript 5和2015+特性在浏览器上大量可用,比如箭头函数、数组。地图,字符串。padStart和模板字符串。从几年开始,可以编写跨浏览器的单行rgb2hex:

几点rgb2hex = (rgb) = > ' # {rgb美元。竞赛(d - ^ rgb (\), s * (\ d + s), \ * (d +) \)美元/片(1))。地图(n =>帕特森(n, 10), to弦(16)。padStart(2,‘0’)。加入(")的 //用你想要的… 控制台日志(rgb2hex (rgb(0,0,0)’) 控制台.log(rgb2hex('rgb(255, 255) 控制台日志(rgb2hex (rgb(255,0,0)’) 控制台(rgb2十六克('rgb(38,170, 90)

它的工作原理是使用正则表达式来获取rgb字符串中的每个数字,slice(1)只获得数字(匹配的第一个结果是完整的字符串本身),map迭代每个数字,每次迭代转换为parseInt的Number,然后返回到十六进制字符串(通过16进制转换),如果需要通过padStart添加零。最后,将每个转换/调整的数字连接到一个以'#'开头的唯一字符串。

当然,我们可以毫不费力地将其扩展为一行代码rgba2hex:

const rgba2hex = (rgba) => `#${rgba.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)$/).slice(1).map((n, i) => (i === 3 ? Math.round(parseFloat(n) * 255) : parseFloat(n)).toString(16).padStart(2, '0').replace('NaN', '')).join('')}` // Now it doesn't matter if 'rgb' or 'rgba'... console.log(rgba2hex('rgb(0,0,0)')) console.log(rgba2hex('rgb(255, 255, 255)')) console.log(rgba2hex('rgb(255,0,0)')) console.log(rgba2hex('rgb(38, 170, 90)')) console.log(rgba2hex('rgba(255, 0, 0, 0.5)')) console.log(rgba2hex('rgba(0,255,0,1)')) console.log(rgba2hex('rgba(127,127,127,0.25)'))

就是这样。但如果您想深入了解旧式JavaScript世界,请继续阅读。


原2010年答案

以下是我根据@Matt的建议写的更清晰的解决方案:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\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]);
}

一些浏览器已经将颜色返回为十六进制(Internet Explorer 8及以下版本)。如果你需要处理这些情况,只需要在函数中添加一个条件,就像@gfrobenius建议的那样:

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\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]);
}

如果你正在使用jQuery并且想要一个更完整的方法,你可以使用自jQuery 1.4.3以来提供的CSS Hooks,就像我在回答这个问题时所展示的:我可以强制jQuery. CSS ("backgroundColor")以十六进制格式返回吗?