javascript 验证 css 颜色名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6386090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating css color names
提问by SystemicPlural
I've written a jQuery plugin that accepts css colors for some of its parameters.
我编写了一个 jQuery 插件,它接受一些参数的 css 颜色。
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?
我想验证它们。如果它只是一个十六进制或 rgb 值,我可以使用正则表达式来做到这一点,但是如何在不使插件膨胀的情况下验证所有 147 个有效颜色名称?
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?
我想知道是否有某种方法可以尝试应用样式(可能使用 jquery),然后在它无效时从浏览器中捕获错误?
Edit: powtac and Pantelis came up with a solution, but they both missed edge cases, so I am including a full solution here:
编辑:powtac 和 Pantelis 提出了一个解决方案,但他们都错过了边缘情况,所以我在这里提供了一个完整的解决方案:
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;
};
回答by Wk_of_Angmar
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.
当有问题的字符串与测试颜色相同时,此页面上发布的所有解决方案都是不正确的。当然,您可以使用不太可能的颜色选择,但我更愿意选择 100% 的成功率。
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.
OP 在他的代码中有一个错字(请参阅带有冒号的条件),并且不测试“#28e32a”,因此该颜色将失败,并且正则表达式将折叠颜色中的空白,因此“#28e 32a”会(错误地) ) 经过。
In normal JavaScript, this should have 100% success:
在普通的 JavaScript 中,这应该 100% 成功:
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/
回答by DaveAlger
I know this question is fairly old but I came up with a pure javascript solutionfor checking colors which seems to work in every browser and wanted to share it
我知道这个问题已经很老了,但我想出了一个纯 javascript 解决方案来检查颜色,它似乎适用于每个浏览器并想分享它
This function uses the browser to convert any input string into a CSS color string (if possible)
此函数使用浏览器将任何输入字符串转换为 CSS 颜色字符串(如果可能)
function getColorCSS(c) {
var ele = document.createElement("div");
ele.style.color = c;
return ele.style.color.replace(/\s+/,'').toLowerCase();
}
Let's take a look at the function output based on different inputs...
我们来看看基于不同输入的函数输出...
INVALID INPUTS
无效输入
Basically anytime the browser can't figure out how to render the input string as a color an empty string
is returned which makes this tiny function perfect for detecting invalid color strings!
基本上任何时候浏览器都无法弄清楚如何将输入字符串渲染为颜色empty string
并返回,这使得这个小函数非常适合检测无效的颜色字符串!
redd
,#f0gf0g
,#1234
,f00
,rgb(1,2)
,rgb(1,2,3.0)
,rgb(1,2,3,4)
,rgba(100,150,200)
. . . chrome
. . . firefox
. . . internet explorer
redd
,#f0gf0g
,#1234
,f00
,rgb(1,2)
,rgb(1,2,3.0)
,rgb(1,2,3,4)
,rgba(100,150,200)
. . . 铬合金
. . . 火狐
. . . IE浏览器
VALID INPUTS
有效输入
aqua
aqua
. . . chromeaqua
. . . firefoxaqua
. . . internet explorer
aqua
aqua
. . . 铬合金aqua
. . . 火狐aqua
. . . IE浏览器
pink
rgb(255,192,203)
. . . chromeconverts all valid html color names to rgb format except for the following 17 and I'm not really sure why["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"]
pink
. . . firefoxpink
. . . internet explorer
pink
rgb(255,192,203)
. . . chrome将所有有效的 html 颜色名称转换为 rgb 格式,以下 17 除外,我不确定为什么["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow"]
pink
. . . 火狐pink
. . . IE浏览器
#f00
,#ff0000
,rgb(255,0,0)
rgb(255,0,0)
. . . chromergb(255,0,0)
. . . firefoxrgb(255,0,0)
. . . internet explorer
#f00
,#ff0000
,rgb(255,0,0)
rgb(255,0,0)
. . . 铬合金rgb(255,0,0)
. . . 火狐rgb(255,0,0)
. . . IE浏览器
rgba(255,0,0,1.0)
,rgba(255,0,0,100)
rgb(255,0,0)
. . . chromeconvertsrgba
torgb
anytime alpha is1.0
or greater since it's fully opaque anyway (probably for performance)rgb(255,0,0)
. . . firefoxdoes the same thing as chromergba(255,0,0,1)
. . . internet explorerconverts the alpha param from1.0
or greater to1
rgba(255,0,0,1.0)
,rgba(255,0,0,100)
rgb(255,0,0)
. . . chrome转换rgba
为rgb
alpha1.0
或更大的任何时间,因为它无论如何都是完全不透明的(可能是为了性能)rgb(255,0,0)
. . . firefox和 chrome 做同样的事情rgba(255,0,0,1)
. . . Internet Explorer将 alpha 参数从1.0
或更大转换为1
rgba(0,255,0,0.5)
rgba(0,255,0,0.498039)
. . . chromereturns something different than the other browsers (possibly trading accuracy for performance)rgba(0,255,0,0.5)
. . . firefoxrgba(0,255,0,0.5)
. . . internet explorer
rgba(0,255,0,0.5)
rgba(0,255,0,0.498039)
. . . chrome返回的东西与其他浏览器不同(可能为了性能而交易准确性)rgba(0,255,0,0.5)
. . . 火狐rgba(0,255,0,0.5)
. . . IE浏览器
rgba(0,0,255,0.0)
,rgba(0,0,255,-100)
rgba(0,0,255,0)
. . . chromeconverts the alpha param from0.0
or lower to0
rgba(0,0,255,0)
. . . firefoxdoes the samergba(0,0,255,0)
. . . internet explorerdoes the same
rgba(0,0,255,0.0)
,rgba(0,0,255,-100)
rgba(0,0,255,0)
. . . chrome将 alpha 参数从0.0
或低于0
rgba(0,0,255,0)
. . . firefox做同样的事情rgba(0,0,255,0)
. . . Internet Explorer也是如此
rgba(0,0,0,0)
,rgba(0,0,0,-100)
rgba(0,0,0,0)
. . . chrometransparent
. . . firefoxconverts only this onergba
instance with all parameters set to0
to the wordtransparent
(strange)rgba(0,0,0,0)
. . . internet explorer
rgba(0,0,0,0)
,rgba(0,0,0,-100)
rgba(0,0,0,0)
. . . 铬合金transparent
. . . firefox只转换这一个rgba
实例,所有参数都设置为0
单词transparent
(奇怪)rgba(0,0,0,0)
. . . IE浏览器
hsl(180,50%,50%)
rgb(63,191,191)
. . . chrome- ff
rgb(63,191,191)
. . . firefox - ie
hsl(180,50%,50%)
. . . internet explorer
hsl(180,50%,50%)
rgb(63,191,191)
. . . 铬合金- ff
rgb(63,191,191)
。. . 火狐 - 即
hsl(180,50%,50%)
。. . IE浏览器
hsl(x,x,0%)
rgb(0,0,0)
. . . chromergb(0,0,0)
. . . firefoxhsl(0,0%,0%)
. . . internet explorerconverts any hsl representation ofblack
to this
hsl(x,x,0%)
rgb(0,0,0)
. . . 铬合金rgb(0,0,0)
. . . 火狐hsl(0,0%,0%)
. . . Internet Explorer将 的任何 hsl 表示转换black
为此
hsl(x,x,100%)
rgb(255,255,255)
. . . chromergb(255,255,255)
. . . firefoxhsl(0,0%,100%)
. . . internet explorerconverts any hsl representation ofwhite
to this
hsl(x,x,100%)
rgb(255,255,255)
. . . 铬合金rgb(255,255,255)
. . . 火狐hsl(0,0%,100%)
. . . Internet Explorer将 的任何 hsl 表示转换white
为此
hsla(180,50%,50%,1.0)
,hsla(180,50%,50%,100)
rgba(63,191,191,1)
. . . chromergba(63,191,191,1)
. . . firefoxhsla(180,50%,50%,1)
. . . internet explorer
hsla(180,50%,50%,1.0)
,hsla(180,50%,50%,100)
rgba(63,191,191,1)
. . . 铬合金rgba(63,191,191,1)
. . . 火狐hsla(180,50%,50%,1)
. . . IE浏览器
hsla(180,50%,50%,0.5)
rgba(63,191,191,0.498039)
. . . chromergba(63,191,191,0.5)
. . . firefoxhsla(180,50%,50%,0.5)
. . . internet explorer
hsla(180,50%,50%,0.5)
rgba(63,191,191,0.498039)
. . . 铬合金rgba(63,191,191,0.5)
. . . 火狐hsla(180,50%,50%,0.5)
. . . IE浏览器
hsla(0,0%,0%,0.0)
,hsla(0,0%,0%,-100)
rgba(0,0,0,0)
. . . chrometransparent
. . . firefoxis consistent but this conversion still seems strangehsla(180,50%,50%,0)
. . . internet explorer
hsla(0,0%,0%,0.0)
,hsla(0,0%,0%,-100)
rgba(0,0,0,0)
. . . 铬合金transparent
. . . firefox是一致的,但这种转换似乎仍然很奇怪hsla(180,50%,50%,0)
. . . IE浏览器
Wow, I can hardly believe I just spent 2 hours testing that function in different browsers!
I guess I may as well demo using the function while I'm at it...
哇,我简直不敢相信我只花了 2 个小时在不同的浏览器中测试了该功能!
我想我也可以在使用该功能时进行演示...
function getColorCSS(c) {
var ele = document.createElement("div");
ele.style.color = c;
return ele.style.color.split(/\s+/).join('').toLowerCase();
}
function isColorValid(c) {
var s = getColorCSS(c);
return (s) ? true : false;
}
function isColorTransparent(c) {
var s = getColorCSS(c);
return (
s === "transparent" ||
s.substring(0,4) === "rgba" && +s.replace(/^.*,(.+)\)/,'') <= 0 ||
s.substring(0,4) === "hsla" && +s.replace(/^.*,(.+)\)/,'') <= 0
);
}
function isColorWhite(c) {
var s = getColorCSS(c);
return [
"white",
"rgb(255,255,255)",
"rgba(255,255,255,1)",
"hsl(0,0%,100%)",
"hsla(0,0%,100%,1)"
].indexOf(s) > -1;
}
function isColorBlack(c) {
var s = getColorCSS(c);
return [
"black",
"rgb(0,0,0)",
"rgba(0,0,0,1)",
"hsl(0,0%,0%)",
"hsla(0,0%,0%,1)"
].indexOf(s) > -1;
}
function checkColorString() {
var c = document.getElementById("c").value;
if (c === "") {
document.getElementsByTagName("body")[0].style.backgroundColor = 'transparent';
document.getElementById("result").innerHTML = '';
}
else if (isColorValid(c)) {
if (isColorTransparent(c)) {
document.getElementsByTagName("body")[0].style.backgroundColor = 'transparent';
document.getElementById("result").innerHTML = '<span style="color:#dadada;">TRANSPARENT</span>';
}
else if (isColorWhite(c)) {
document.getElementsByTagName("body")[0].style.backgroundColor = getColorCSS(c);
document.getElementById("result").innerHTML = '<span style="color:black;">WHITE</span>';
}
else if (isColorBlack(c)) {
document.getElementsByTagName("body")[0].style.backgroundColor = getColorCSS(c);
document.getElementById("result").innerHTML = '<span style="color:white;">BLACK</span>';
}
else {
document.getElementsByTagName("body")[0].style.backgroundColor = getColorCSS(c);
document.getElementById("result").innerHTML = getColorCSS(c);
}
}
else {
document.getElementsByTagName("body")[0].style.backgroundColor = 'transparent';
document.getElementById("result").innerHTML = '<span style="font-size:42px;color:#dadada;">☹</span>';
}
}
var eventList = ["change", "keyup", "paste", "input", "propertychange"];
for(event of eventList) {
document.getElementById("c").addEventListener(event, function() {
checkColorString();
});
}
#c {
width: 300px;
padding: 6px;
font-family: courier;
}
#result {
font-family: courier;
font-size: 24px;
padding: 12px 6px;
}
<input id="c" placeholder="Enter any valid CSS color..."></input>
<div id="result"></div>
回答by powtac
You could simply set the color to a dummy element and then check if the element's value is something other than white.
您可以简单地将颜色设置为虚拟元素,然后检查元素的值是否不是白色。
colorToTest = 'lime'; // 'lightgray' does not work for IE
$('#dummy').css('backgroundColor', 'white');
$('#dummy').css('backgroundColor', colorToTest);
if ($('#dummy').css('backgroundColor') != 'rgb(255, 255, 255)' || colorToTest == 'white') {
alert(colorToTest+' is valid');
}
回答by Pantelis
function test(myColor) {
var valid = $('#test').css('color');
$('#test').css('color', myColor);
if (valid == $('#test').css('color')) alert("INVALID COLOR");
else {
alert("VALID");
$('#test').css('color', valid);
}
}
test("TATATA");
test("white");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">asdasdasdasd</div>
It is hastily written but it works.
它是匆忙写的,但它有效。
回答by Nicola Peluchetti
I think you can use the script from this pagethat does exactly what you want: you pass a string to it and tries to figure out the color. Ok, it's not exactly what you wanted to do but it should work.
我认为您可以使用此页面中的脚本来满足您的需求:您将一个字符串传递给它并尝试找出颜色。好的,这不是您想要做的,但它应该可以工作。
I think that in any case at some point you should do a name lookup (i don't think there is some magic way to determine the hex value from the string "light blue") so just snatch the work some one else has done (the script is by Stoyan Stefanov which is very good at javascript, i've read some good books from him, and if he does a lookup, well, i don't think there is another solution)
我认为在任何情况下,您都应该进行名称查找(我认为没有什么神奇的方法可以从字符串“light blue”中确定十六进制值),因此只需抢夺其他人已经完成的工作(脚本是由 Stoyan Stefanov 编写的,他非常擅长 javascript,我从他那里读了一些好书,如果他查了一下,好吧,我认为没有其他解决方案)
回答by Valen
crazy thought
疯狂的想法
function isValidCssColor(c){
// put !! to normalize to boolean
return [document.head.style.color = c, document.head.style.color][1];
}
I believe it works (only not when your pages doesn't not have a head
element, somehow)
我相信它有效(仅当您的页面没有head
元素时才有效)