Javascript - check if string is valid CSS color?

前端 未结 6 1353
一生所求
一生所求 2021-01-01 23:25

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?

I have code that generates contro

6条回答
  •  抹茶落季
    2021-01-02 00:19

    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
    

    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.

    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.

提交回复
热议问题