jQuery's css() method allows developers to retrieve an element's background color value as an RGB string. While this is useful, there may be instances where a hexadecimal color value is preferred.
To obtain the hex value, consider the following script:
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 supports both RGB and RGBA color formats, making it versatile for various scenarios. To use it, simply provide the RGB or RGBA value as an input:
const hexValue = rgba2hex('rgb(255, 255, 255)'); // Returns '#FFFFFF'
The above is the detailed content of How Can I Convert RGB to Hexadecimal Color Values Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!