如何获取十六进制颜色值而不是RGB值?

208

使用以下jQuery代码可以获取元素背景色的RGB值:

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

有没有办法获取十六进制值而非RGB值?


2
在相关主题上,更多(且可以说更好)的将十六进制和RGB颜色之间进行转换的方法在这里:https://dev59.com/7G035IYBdhLWcg3wGMDa。这个轮子已经被重复发明了足够多次来建造一列火车了。我希望其中一个流行的JS库能够提供一个比less更简单的实用函数。 - Michael Scheper
请记住,某些浏览器返回rgba(#,#,#,#)格式,例如rgba(0,0,0,0)表示透明而不是黑色。第四个值是不透明度,1.0表示完全颜色100%,0.5表示50%。 - Twelve24
理想情况下,我们应该能够告诉浏览器使用哪种格式。我有这样的印象,与浏览器相关的人们更倾向于使用RGBA而不是备受喜爱的十六进制代码。 - run_the_race
25个回答

1

我的精简版

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


1

对于所有的函数式编程爱好者,这里提供一种略有函数式风格的方法 :)

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)

1

将RGB转换为十六进制

我正在使用Jasmine protractor,但是遇到了错误,例如- 预期 [ '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);

        })

       

你可以用 *.padStart(2, "0") 替换 if (r.length == 1) ... r = "0" + r; - Fabrice T

0

嗨,这是我使用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)); 
}

0

colord 包可能是最好的选择,它小巧而强大。

import { colord } from "colord";

colord("rgb(192, 192, 192)").toHex();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接