Is there a built-in function that would convert a color by name into its hex representation? Like I want to pass 'white' and receive '#FFFFFF'. I really want to avoid coding all hundred if's myself :)
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
No, but using the list here you could create one. Something like this:
Quick code for HEX / RGB values only, might be useful to someone, and can be adapted to include names: pull the whole object in the for loop, check the name and if it matches you've got your hex / rbg. They are taken from here: http://www.colourlovers.com/web/blog/2008/04/22/all-120-crayon-names-color-codes-and-fun-facts
Most importantly, please notice the correct spelling of "colour" :P
Edit: I've cleaned this up a bit and made a gist and demo of it. The basic approach remains the same.
The "add an element to the DOM and check its ComputedStyle" approach seems a little complex to me — you need to add it and check it and remember to remove it and you're changing the DOM just to compute a color and does it cause reflow? So here's a solution based on a temporary (and never rendered)
<canvas>
:Note that this lets you use anything that's a valid canvas fillStyle, so if you want to gin up a 1 pixel pattern from an image, it'll tell you the color of that as well.
I've tested this in reasonably modern versions of IE, Chrome, Safari, and Firefox.
IE8 getComputedStyle polyfill if needed
Not that's built-in, as far as I know. It would be kind of a hack, but I think you could create an invisible div, set its CSS background property to the named color, then use JS to get the background color of the div, then delete the div.