Home > Web Front-end > JS Tutorial > How to Convert RGB to Hex Color Values in jQuery?

How to Convert RGB to Hex Color Values in jQuery?

Barbara Streisand
Release: 2024-12-17 00:05:25
Original
964 people have browsed it

How to Convert RGB to Hex Color Values in jQuery?

Obtaining Hex Color Values from RGB Colors in jQuery

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('')}`
Copy after login

This function addresses both RGB and RGBA formats, ensuring versatility.

Example Usage:

const element = $('#selector');
const rgbColor = element.css('backgroundColor');
const hexColor = rgba2hex(rgbColor);
Copy after login

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('')}`
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template