194

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

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

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

4

23 回答 23

184

TLDR

使用这个干净的单行函数同时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+ 功能在浏览器上大量可用,例如箭头函数Array.mapString.padStart模板字符串。所以现在可以写一个单行rgb2hex

const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`

// Use as you wish...
console.log(rgb2hex('rgb(0,0,0)'))
console.log(rgb2hex('rgb(255, 255, 255)'))
console.log(rgb2hex('rgb(255,0,0)'))
console.log(rgb2hex('rgb(38, 170, 90)'))

基本上,我们使用正则表达式来获取rgb字符串中的每个数字,slice(1)仅获取数字(的第一个结果match是完整的字符串本身),map遍历每个数字,每次迭代转换为Numberwith parseInt,然后返回十六进制String(通过base-16转换),如果需要通过添加零padStart。最后,只有join每个转换/调整的数字都以.String开头'#'

当然,我们可以毫不费力地将其扩展为单行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") 以十六进制格式返回吗?

于 2010-09-02T13:52:22.170 回答
142
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];
 }

来源

于 2009-11-16T07:55:44.880 回答
64

大多数浏览器在使用时似乎返回 RGB 值:

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

只有 IE(目前只测试了 6 个)返回十六进制值。

为避免 IE 中出现错误消息,您可以将函数包装在 if 语句中:

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     } else {
          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]); 
     }
}
于 2010-11-03T19:01:22.123 回答
23

更新了@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 值,但不使用它。

于 2010-10-19T18:26:58.703 回答
11

这是一个不使用 jQuery 的 ES6 one liner:

var rgb = document.querySelector('#selector').style['background-color'];
return '#' + rgb.substr(4, rgb.indexOf(')') - 4).split(',').map((color) => parseInt(color).toString(16).padStart(2, '0')).join('');
于 2015-11-04T00:52:19.167 回答
6

这是一个也检查透明的版本,我需要这个,因为我的对象是将结果插入到样式属性中,其中十六进制颜色的透明版本实际上是单词“透明”..

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     }
     else if ( rgb == 'rgba(0, 0, 0, 0)' ) {
         return 'transparent';
     }
     else {
          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]); 
     }
}
于 2013-02-13T09:38:16.910 回答
5

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

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));
}

jsfiddle

于 2014-09-30T17:16:28.360 回答
4

与@Jim F 答案相同的答案, 但ES6语法,因此,指令更少:

const rgb2hex = (rgb) => {
  if (rgb.search("rgb") === -1) return rgb;
  rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
  const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2);
  return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
};
于 2016-11-30T18:42:57.443 回答
4

尝试

// 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 - 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``

console.log(rgb2hex("rgb(12,233,43"));

于 2019-10-15T08:01:17.670 回答
3

从引导颜色选择器中获取的颜色类

// 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()
于 2013-06-08T00:05:01.357 回答
3

可读 && 免费 Reg-exp(无 Reg-exp)

我创建了一个使用可读基本函数且没有 reg-exps 的函数。
该函数接受 hex、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);
}
于 2015-05-21T18:30:25.300 回答
3

只是添加到上面@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。

谢谢

于 2017-01-15T19:42:43.047 回答
2

这个看起来好一点:

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]);
        }
    }
}
于 2014-04-20T18:50:51.237 回答
1

这是我发现的一个不会在 IE 中引发脚本错误的解决方案:http: //haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx

于 2011-05-30T18:30:42.623 回答
1

Steven Pribilinskiy 的答案去掉了前导零,例如 #ff0000 变为 #ff00。

一种解决方案是在最后 2 位数字后面附加一个前导 0 和子字符串。

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ String('0' + Number(rgb[0]).toString(16)).slice(-2) + String('0' + Number(rgb[1]).toString(16)).slice(-2) + String('0' + Number(rgb[2]).toString(16)).slice(-2);
于 2014-07-09T11:47:24.050 回答
1

由于问题是使用 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');
于 2017-04-13T06:05:16.050 回答
1

改进的功能“十六进制”

function hex(x){
    return isNaN(x) ? "00" : hexDigits[x >> 4] + hexDigits[x & 0xf];
    // or option without hexDigits array
    return (x >> 4).toString(16)+(x & 0xf).toString(16);
}
于 2021-02-22T04:54:23.293 回答
0

这是我的解决方案,还通过使用参数来大写,并检查提供的字符串中是否存在其他可能的空格和大写。

var a = "rgb(10, 128, 255)";
var b = "rgb( 10, 128, 255)";
var c = "rgb(10, 128, 255 )";
var d = "rgb ( 10, 128, 255 )";
var e = "RGB ( 10, 128, 255 )";
var f = "rgb(10,128,255)";
var g = "rgb(10, 128,)";

var rgbToHex = (function () {
    var rx = /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;

    function pad(num) {
        if (num.length === 1) {
            num = "0" + num;
        }

        return num;
    }

    return function (rgb, uppercase) {
        var rxArray = rgb.match(rx),
            hex;

        if (rxArray !== null) {
            hex = pad(parseInt(rxArray[1], 10).toString(16)) + pad(parseInt(rxArray[2], 10).toString(16)) + pad(parseInt(rxArray[3], 10).toString(16));

            if (uppercase === true) {
                hex = hex.toUpperCase();
            }

            return hex;
        }

        return;
    };
}());

console.log(rgbToHex(a));
console.log(rgbToHex(b, true));
console.log(rgbToHex(c));
console.log(rgbToHex(d));
console.log(rgbToHex(e));
console.log(rgbToHex(f));
console.log(rgbToHex(g));

jsfiddle 上

jsperf上的速度比较

进一步的改进可能是trim()rgb字符串

var rxArray = rgb.trim().match(rx),
于 2013-04-27T13:45:40.390 回答
0

我美丽的非标解决方案

HTML

<div id="selector" style="background-color:#f5b405"></div>

jQuery

$("#selector").attr("style").replace("background-color:", "");

结果

#f5b405
于 2018-03-02T06:36:58.343 回答
0

将 RGB 转换为十六进制

我正在使用 Jasmine 量角器,但我遇到了像 - Expected [ 'rgba(255, 255, 255, 1)' ] to contain '#fff'. 下面的函数这样的错误对我来说很好。

function RGBAToHexA(test:string) {
let sep = test.toString().indexOf(",") > -1 ? "," : " ";
const rgba = test.toString().substring(5).split(")")[0].split(sep);
console.log(rgba)
let r = (+rgba[0]).toString(16),
  g = (+rgba[1]).toString(16),
  b = (+rgba[2]).toString(16),
  a = Math.round(+rgba[3] * 255).toString(16);

    if (r.length == 1)
        r = "0" + r;
    if (g.length == 1)
        g = "0" + g;
    if (b.length == 1)
        b = "0" + b;
    if (a.length == 1)
        a = "0" + a;

return "#" + r + g + b + a;

}

describe('Check CSS', function() {
 
it('should check css of login page', async function(){
        browser.waitForAngularEnabled(true);
        browser.actions().mouseMove(element(by.css('.btn-auth, .btn-auth:hover'))).perform(); // mouse hover on button
        csspage.Loc_auth_btn.getCssValue('color').then(function(color){
            console.log(RGBAToHexA(color))
            expect( RGBAToHexA(color)).toContain(cssData.hoverauth.color);

        })

       
于 2020-09-01T19:47:25.430 回答
0

对于所有函数式编程爱好者,这里有一个有点函数式的方法:)

const getHexColor = (rgbValue) =>
  rgbValue.replace("rgb(", "").replace(")", "").split(",")
    .map(colorValue => (colorValue > 15 ? "0" : "") + colorValue.toString(16))
    .reduce((acc, hexValue) => acc + hexValue, "#")

然后像这样使用它:

const testRGB = "rgb(13,23,12)"
getHexColor(testRGB)
于 2020-11-26T03:37:17.667 回答
0

我的精简版

//Function to convert rgb color to hex format
function rgb2hex(rgb) {
    if(/^#/.test(rgb))return rgb;// if returns colors as hexadecimal
    let re = /\d+/g;
    let hex = x => (x >> 4).toString(16)+(x & 0xf).toString(16);
    return "#"+hex(re.exec(rgb))+hex(re.exec(rgb))+hex(re.exec(rgb));
}

于 2021-02-22T04:13:57.497 回答
0

完整案例(rgb、rgba、透明...等)解决方案(coffeeScript)

 rgb2hex: (rgb, transparentDefault=null)->
    return null unless rgb
    return rgb if rgb.indexOf('#') != -1
    return transparentDefault || 'transparent' if rgb == 'rgba(0, 0, 0, 0)'
    rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
    hex = (x)->
      ("0" + parseInt(x).toString(16)).slice(-2)

    '#' + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3])
于 2021-02-27T02:09:00.343 回答