Javascript-检查字符串是否为有效的CSS颜色? [英] Javascript - check if string is valid CSS color?

查看:176
本文介绍了Javascript-检查字符串是否为有效的CSS颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果颜色字符串是数字,则可以使用 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?

我有一些代码可以根据colors参数动态生成控件。但是,除了颜色以外,可能还有 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()检查,因为颜色可能是绿色 红色 等)。

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颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆