Color uniformity in javascript

Is there a way to check if two strings representing colors are hexadecimal, rgb, rgba or in word form are equal.

For example, they will be equal

"red" and "# ff0000"
"red" and "# f00"
"red" and "rgb (255, 0, 0)"
"# ff0000" and "rgba (255, 0, 0, 255)"

What I'm trying to do is combine two or more elements together if their colors are the same, but sometimes the colors are presented differently.

I checked the equality of the string element.style.color, but then I ran into this problem. Would be better with a different approach?

The answer to the question, and only out of curiosity, is one browser the "dark blue" rgb value equal to other browsers of the "dark blue" rgb value for all colors?

+4
source share
2 answers

You can use a little color

https://bgrins.imtqy.com/TinyColor/

https://bgrins.imtqy.com/TinyColor/tinycolor.js

you just need to pass the color name and it will return the color name in hexadecimal, rgb, etc.

var tiny = tinycolor(color);
var hexString=  tiny.toHexString();
var hex8String=  tiny. tiny.toHex8String();

and there are other similar methods

tiny.toRgbString()
tiny.toHslString()
tiny.toHsvString()
tiny.toName()
tiny.getFormat()

after you got the whole format, then you can compare using string equality. Please check out the demo above.

There is one method for comparing colors.

tinycolor.equals(color1, color2) 
+3
source

window.getComputedStyle(el).backgroundColorreturns the color in the format rgb(r, g, b).

jQuery.css() .

: , , IE:)

+2

Source: https://habr.com/ru/post/1599437/


All Articles