Problem:
In jQuery, the css() method obtains an element's background color as Red, Green, and Blue (RGB) values in the format rgb(r, g, b). However, a common requirement is to retrieve the equivalent hex color value, such as #FFFFFF.
Solution:
The traditional method of attaining a hex value from RGB involves manual conversion, which can be tedious. Fortunately, a concise one-line function achieves this:
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('')}`
This function addresses both RGB and RGBA formats, ensuring versatility.
Example Usage:
const element = $('#selector'); const rgbColor = element.css('backgroundColor'); const hexColor = rgba2hex(rgbColor);
Updated Answer for Modern Browsers:
Since the original solution, browser support for ECMAScript 2015 features has improved significantly. This allows for a more streamlined and concise RGB to hex conversion:
const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`
This function offers similar functionality, catering specifically to RGB color formats.
The above is the detailed content of How to Convert RGB to Hex Color Values in jQuery?. For more information, please follow other related articles on the PHP Chinese website!