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

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

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


当前回答

从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()

其他回答

// 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”);

我的精简版

//函数将rgb颜色转换为十六进制格式 函数rgb2hex(rgb) { If (/^#/.test(rgb))返回rgb;// If返回十六进制颜色 设re = /\d+/g; 让十六进制= x = > (x > > 4) .toString (16) + (x & 0 xf) .toString (16); 返回“#”+十六进制(re.exec (rgb)) +十六进制(re.exec (rgb)) +十六进制(re.exec (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 rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var r   = parseInt(rgb[0], 10);
var g   = parseInt(rgb[1], 10);
var b   = parseInt(rgb[2], 10);
var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);

更简洁的一句话:

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);

强制jQuery总是返回十六进制:

$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle) {
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        }
        if (bg.search("rgb") == -1) {
            return bg;
        } else {
            bg = bg.match(/\d+/g);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
        }
    }
}

博士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")以十六进制格式返回吗?