问题
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