使用下面的jQuery将获得元素背景颜色的RGB值:
$('#selector').css('backgroundColor');
有没有办法得到十六进制值而不是RGB?
使用下面的jQuery将获得元素背景颜色的RGB值:
$('#selector').css('backgroundColor');
有没有办法得到十六进制值而不是RGB?
当前回答
博士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")以十六进制格式返回吗?
其他回答
下面是我发现的一个解决方案,它不会在IE中抛出脚本错误: http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx
从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()
将RGB转换为十六进制
我用的是茉莉花量角器,结果出现了一些错误 -期望['rgba(255, 255, 255, 1)']包含'#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);
})
大多数浏览器似乎在使用时返回RGB值:
$('#selector').css('backgroundColor');
只有i.e.(到目前为止只测试了6个)返回十六进制值。
为了避免在i.e.中出现错误消息,你可以将函数包装在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]);
}
}
短
// 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”);