Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does object.style.color only return rgb

Tags:

javascript

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
like image 402
Rod Avatar asked Jul 26 '12 13:07

Rod


People also ask

What is rgb color in CSS?

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.

What is the correct syntax for RGB color format?

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 ')'.


1 Answers

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;
like image 148
Danilo Valente Avatar answered Sep 28 '22 10:09

Danilo Valente