Test if CSS color name exists
I have an application where the user can type in a color name, say blue
, once he/she has done that, a div will turn into that color.
The code is pretty simple at the moment:
<div class="colorBo开发者_开发技巧x" style="background-color: <%= color.name %>;">
</div>
Is it possible to check whether or not that particular color exists? At the moment I can only think of one solution:
Loop through a list of color names, like this one, but isn't there a more elegant way? E.g
CSS.exists("blue")
=> true
Also, I don't want the user to enter a color hex.
- if you get a color with jquery (e.g.
$(...).css('background-color')
) it will return anRGB
format color even if no color was setted on that element - a css value will stick to it's property only if it's a valid property otherwise:
- it will hold its previous value if it has any
- it will hold an empty string (in this case) or maybe
undefined
...
so if you change a color with a fake name since it wouldn't set for that property, the property will hold previous valid color (if it has one) and when you want to check that you will check an old valid color name not a new invalid one.
This should work. Call if after the user sets the color;
function isColorValid(element, value) {
return element && element.style.backgroundColor === val;
}
EDIT: jsFiddle
The Color gem/Color::CSS is what you want:
Returns the RGB colour for name or nil if the name is not valid.
From your question, it appears that you would like to do check on the server itself. However, recognition of colors is a browser specific behavior and hence a round trip to browser would be required.
Following is a way. I would be interested in seeing if someone has something more elegant. We assume you are using jquery.
Put a 'test' div in your html. HTML:
<div id="test"></div>
JS:
function color_exists(color) {
if (color == 'white') {
return true;
}
$('#test').css('backgroundColor', color);
if ($('#test').css('backgroundColor') == color) {
return true;
} else {
return false;
}
}
We rely on the fact that the browser would simply ignore a color value if it cannot recognize it.
精彩评论