问题描述
如果颜色字符串是数字,那么我们可以使用 RegExp
来检查它是否是有效的 CSS 颜色.但如果是一个词呢?
If a color string is a number, then we can use a RegExp
to check if it's a valid CSS color. But what if it's a word?
我有从颜色参数动态生成控件的代码.但是除了颜色之外,还可以是 null
、""
或随机单词.有没有办法用Javascript检查颜色名称?
I have code that generates controls dynamically from colors arguments. But instead of color, there could be null
, ""
, or random words. Is there a way to check color name with Javascript?
更新:非常感谢您的精彩回答!:)我的最终版本如下(添加了一个 toLowerCase()
检查,因为颜色可能是 "Green"
、"Red"
等).
Update: Thank you much for the great answer! :)My final version is below (added a toLowerCase()
check because the color could be "Green"
, "Red"
, etc.).
function isValidColor(strColor) {
var s = new Option().style;
s.color = strColor;
// return 'false' if color wasn't assigned
return s.color == strColor.toLowerCase();
}
推荐答案
这里有一个简单的函数,用于检查当前浏览器中的颜色名称支持:
Here's a simple function that checks color name support in the current browser:
function isColor(strColor){
var s = new Option().style;
s.color = strColor;
return s.color == strColor;
}
// try it out
isColor("red"); // true
isColor("reds"); // false
由于无效的 CSS 属性值不会持续存在,我们可以将尝试设置的值与我们打算设置的值进行比较,如果它们匹配,我们就知道颜色/属性是有效的.
Since an invalid CSS property value will not persist, we can compare an attempted set value with the value we meant to set, and if they match, we know the color/property is valid.
请注意,这也将批准十六进制、RGB 等.如果这是您的应用程序的问题,您可以使用一两个 RegExp
将它们筛选出来.
Note this will also approve hex, RGB, etc. You can screen those out with a RegExp
or two if that's an issue for your application.
这篇关于Javascript - 检查字符串是否是有效的 CSS 颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!