如何得到hex颜色值而不是RGB值?

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

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

有没有办法得到hex值,而不是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]; } 

( 来源 )

这里是我写的基于@Mattbuild议的更清洁的解决scheme:

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

某些浏览器已经以hex(Internet Explorer 8和更低版本)的forms返回颜色。 如果您需要处理这些情况,只需在该函数内附加一个条件,如@ gfrobeniusbuild议:

 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”)以hex格式返回吗?

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

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

只有IE(目前只有6个testing)返回hex值。

为了避免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]); } } 

rgba兼容性更新@ErickPetru:

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

我更新了正则expression式以匹配alpha值(如果已定义),但不使用它。

这是一个不使用jQuery的ES6单行代码:

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

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

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

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

我创build了一个使用可读的基本函数并且没有reg-exps的函数。
该函数接受hex,rgb 或rgba CSS格式的颜色,并返回hex表示。
编辑:有parsing出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); } 

色彩类从自举颜色select器采取

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

这个看起来好一些:

 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总是返回hex:

 $.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]); } } } 

函数返回hex元素的背景颜色。

 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

这里有一个解决scheme,我发现不会在IE中抛出脚本错误: http : //haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx

这里是我的解决scheme,也是通过使用参数来检查touppercase ,并在提供的string中检查其他可能的空白和大小写。

 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() rgbstring的进一步改进

 var rxArray = rgb.trim().match(rx), 

史蒂芬Pribilinskiy的回答下降前导零,例如#ff0000成为#ff00。

一个解决scheme是追加最后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); 

像@Jim F答案一样的答案,但ES6的语法,所以,less说明:

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

只是添加到@贾斯汀的答案上面..

它应该是

 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(''); 

正如上面parsingint函数截断前导零,从而产生不正确的5或4个字母的颜色代码可能是…即rgb(216,160,10)产生#d8a0a而它应该是#d8a00a。

谢谢

由于问题是使用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');