environment: JavaScript
object.style.color returns something like
"rgb(255,0,0)"
Is there another return format, like hex?
var colorvariable = document.getElementById('text1').style.color
RGB Value. In CSS, a color can be specified as an RGB value, using this formula: rgb(red, green, blue) Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255. For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others are set to 0.
The format of the RGB Value The format of an RGB value in the functional notation is 'rgb(' followed by a comma-separated list of three numerical values (three integer values(0-255, 0-255, 0-255)) followed by ')'.
If you set:
document.getElementById('text1').style.color = '#000';
It will return #000
.
However, if you set:
document.getElementById('text1').style.color = 'rgb(0,0,0)';
It will return rgb(0,0,0)
, so this returned value depends on the value that was set.
You can use getComputedStyle
to get the color in RGB format and then convert to HEX. See this code:
var hexChars = '0123456789ABCDEF';
var rgb = getComputedStyle(document.body).color.match(/\d+/g);
var r = parseInt(rgb[0]).toString(16);
var g = parseInt(rgb[1]).toString(16);
var b = parseInt(rgb[2]).toString(16);
var hex = '#' + r + g + b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With