Javascript - check if string is valid CSS color?

前端 未结 6 1357
一生所求
一生所求 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:07

    The accepted answer is almost correct, but some color values will be converted on some browsers -- at least Chrome converts hex RGB values #000000 to rgb(0, 0, 0).

    However, if you set the style.color to an invalid value, you will get an empty string when checking it:

    const isColor = (strColor) => {
      const s = new Option().style;
      s.color = strColor;
      return s.color !== '';
    }
    

提交回复
热议问题