In JSColor, how do I get the hex of the color?

ぐ巨炮叔叔 提交于 2019-12-11 03:53:09

问题


Using JSColor, after the user picks a color, how do I get the "hex"?

$("input#colorpicker").css('background-color') => this returns background-color: rgb(107, 132, 255);

But not a hex.


回答1:


I assume that jQuery.css returns the value that was set. Try the following function to convert RGB to HEX:

function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);

    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

colorToHex('rgb(120, 120, 240)')



回答2:


Actually upto an extent this depends on browser that it returns in rgb or hex, anyway check out this threads there are nice discussions about it and there are many solutions as well.

Background-color hex to JavaScript variable

and

How to get hex color value rather than RGB value?

and

Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

and

jquery css color value returns RGB?




回答3:


There is onchange event available:

$("input#colorpicker").change(function() {
    console.log(this.color);
});


来源:https://stackoverflow.com/questions/8868404/in-jscolor-how-do-i-get-the-hex-of-the-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!