Validating css color names

前端 未结 7 1975
孤城傲影
孤城傲影 2020-12-09 16:15

I\'ve written a jQuery plugin that accepts css colors for some of its parameters.

I want to validate them. If it was just a hex or rgb value I could do that with a r

相关标签:
7条回答
  • 2020-12-09 17:02

    crazy thought

    function isValidCssColor(c){
        // put !! to normalize to boolean
        return [
                document.head.style.color = c,
                document.head.style.color,
                document.head.style.color = null
        ][1]; // split it in 3 lines is fine, see snippet
    }
    

    I believe it works (only not when your pages doesn't not have a head element, somehow)

    function isValidCssColor(c){
      document.head.style.color = c;
      let result = document.head.style.color;
      document.head.style.color = null;
      return result;
    }
    
    console.log(isValidCssColor("asdf"));       // <empty string>
    console.log(isValidCssColor("black"));      // black
    console.log(isValidCssColor("#abcdee"));    // rgb(171, 205, 238) // this is browser dependent I guess
    console.log(isValidCssColor("asssdf"));     // <empty string>

    0 讨论(0)
提交回复
热议问题