Validating css color names

前端 未结 7 1996
孤城傲影
孤城傲影 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

    All of the solutions posted on this page are incorrect when the string in question is the same colour as the test colour. Granted, you could use a very unlikely choice of colour, but I would prefer to go for 100% success rate.

    OP has a single typo in his code (see condition with colon), and does not test for "#28e32a", so that colour will fail, and the regex will collapse whitespace within the colour, so "#28e 32a" would (incorrectly) pass.

    In normal JavaScript, this should have 100% success:

    function validTextColour(stringToTest) {
        //Alter the following conditions according to your need.
        if (stringToTest === "") { return false; }
        if (stringToTest === "inherit") { return false; }
        if (stringToTest === "transparent") { return false; }
    
        var image = document.createElement("img");
        image.style.color = "rgb(0, 0, 0)";
        image.style.color = stringToTest;
        if (image.style.color !== "rgb(0, 0, 0)") { return true; }
        image.style.color = "rgb(255, 255, 255)";
        image.style.color = stringToTest;
        return image.style.color !== "rgb(255, 255, 255)";
    }
    

    JSFiddle: http://jsfiddle.net/WK_of_Angmar/xgA5C/

提交回复
热议问题