How can I know if a given string is hex, rgb, rgba or hsl color using javascript/jquery?

前端 未结 2 1876
小鲜肉
小鲜肉 2021-02-08 09:54

I used regex for the hex. /^\\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/ but I dont know what I should for do for finding rgb, rgba and hsl. I am getting the input in strin

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-08 10:23

    I dont know about other browsers but in chrome the color will only be set if its valid:

    var isValidColor = function(color) {
      var el = document.createElement('div');
      el.style.backgroundColor = color;
      return el.style.backgroundColor ? true : false;
    };
    
    console.log(isValidColor('#ff0000')); // true
    console.log(isValidColor('rgb(0, 0)')); // false
    

    It will have it's pitfalls though, because Chrome will do auto rounding of numbers:

    // 0, 0, 256 is not a valid color, but this says yes
    console.log(isValidColor('rgb(0, 0, 256)')); // true
    

提交回复
热议问题