验证css颜色名称 [英] Validating css color names
问题描述
我写了一个jQuery插件,接受css颜色的一些参数。
I've written a jQuery plugin that accepts css colors for some of its parameters.
我想验证它们。如果它只是一个十六进制或rgb值,我可以用正则表达式,但如何验证所有147有效的颜色名称,而不膨胀插件?
I want to validate them. If it was just a hex or rgb value I could do that with a regular expression, but how do I validate all 147 valid color names without bloating the plugin?
我是想知道是否有某种方式尝试应用一个样式(也许与jquery),然后捕获一个错误从浏览器,如果它是无效的?
I was wondering if there is some way of attempting to apply a style (maybe with jquery) and then catching an error from the browser if it is not valid?
编辑:powtac和Pantelis提出了一个解决方案,但他们都错过了边缘情况,所以我包括一个完整的解决方案:
powtac and Pantelis came up with a solution, but they both missed edge cases, so I am including a full solution here:
var validateCssColour = function(colour){
var rgb = $('<div style="color:#28e32a">'); // Use a non standard dummy colour to ease checking for edge cases
var valid_rgb = "rgb(40, 227, 42)";
rgb.css("color", colour);
if(rgb.css('color') == valid_rgb && colour != ':#28e32a' && colour.replace(/ /g,"") != valid_rgb.replace(/ /g,""))
return false;
else
return true;
};
推荐答案
此页面上发布的所有解决方案都不正确所讨论的字符串是与测试颜色相同的颜色。当然,你可以使用一个不太可能的颜色选择,但我更喜欢去100%的成功率。
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在他的代码中有一个错误带冒号),并且不测试#28e32a,因此颜色将失败,正则表达式将折叠颜色内的空格,因此#28e 32a将(不正确地)通过。
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.
在正常的JavaScript中,这应该有100%的成功:
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/
JSFiddle: http://jsfiddle.net/WK_of_Angmar/xgA5C/
这篇关于验证css颜色名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!