Answers:
/^#[0-9A-F]{6}$/i.test('#AABBCC')
详细说明:
^ ->匹配开始
# ->的哈希
[0-9A-F] ->从0到9的任意整数,并从A至F的任何字母
{6} ->前一组恰好出现6次
$ ->匹配端
i ->忽略大小写
如果需要支持3个字符的十六进制代码,请使用以下命令:
/^#([0-9A-F]{3}){1,2}$/i.test('#ABC')
唯一的区别是
[0-9A-F]{6}
被替换为
([0-9A-F]{3}){1,2}
这意味着与其精确匹配6个字符,不如精确匹配3个字符,但匹配1或2次。允许ABC和AABBCC,但不允许ABCD
color: #f00;也将被解释为红色(#ff0000)。
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test("#f00")
/^#([0-9a-f]{3}){1,2}$/i到混合。
/^#[0-9A-F]{3,6}$/i.test('#aabb')也可以通过,但#aabb不是有效的十六进制颜色。
// regular function
function isHexColor (hex) {
return typeof hex === 'string'
&& hex.length === 6
&& !isNaN(Number('0x' + hex))
}
// or as arrow function (ES6+)
isHexColor = hex => typeof hex === 'string' && hex.length === 6 && !isNaN(Number('0x' + hex))
console.log(isHexColor('AABBCC')) // true
console.log(isHexColor('AABBCC11')) // false
console.log(isHexColor('XXBBCC')) // false
console.log(isHexColor('AAXXCC')) // false
这个答案曾经引发误报,因为Number('0x' + hex)它代替了parseInt(hex, 16)。parseInt()将从字符串的开头开始解析,直到到达基数(16)中未包含的字符为止。这意味着它可以解析“ AAXXCC”之类的字符串,因为它以“ AA”开头。
Number()另一方面,仅当整个字符串与基数匹配时才进行解析。现在,Number()它不需要基数参数,但是幸运的是,您可以在数字文字前添加前缀以获取其他半径的数字。
这是一个澄清表:
╭─────────────┬────────────┬────────┬───────────────────╮
│ Radix │ Characters │ Prefix │ Will output 27 │
╞═════════════╪════════════╪════════╪═══════════════════╡
│ Binary │ 0-1 │ 0b │ Number('0b11011') │
│ Octal │ 0-7 │ 0o │ Number('0o33') │
│ Decimal │ 0-9 │ - │ - │
│ Hexadecimal │ 0-9A-F │ 0x │ Number('0x1b') │
╰─────────────┴────────────┴────────┴───────────────────╯
parseInt将接受"abcZab",所以发现"Z"无效(对于基数16),然后忽略它以及它之后的所有内容。然后,它从头开始"abc"并将其转换为2748(这也是的结果parseInt("abcZab", 16),证明这是逻辑上的发生)。顾名思义,parseInt 解析一个字符串。就像您要解析一个以10为基数的单位的数字一样parseInt("10px", 10),您将得到10。你可以看到在这里描述:es5.github.io/#x15.1.2.2(第11步)
这可能是一个复杂的问题。经过几次尝试,我想出了一个相当干净的解决方案。让浏览器为您完成工作。
第1步:创建一个边框样式设置为none的div。可以将div放置在屏幕之外,也可以是页面上不使用边框的任何div。
步骤2:将边框颜色设置为空字符串。该代码可能看起来像这样:
e=document.getElementbyId('mydiv');
e.style.borderColor="";
步骤3:将边框颜色设置为不确定的颜色。
e.style.borderColor=testcol;
第4步:检查颜色是否实际更改。如果testcol无效,则不会发生任何更改。
col2=e.style.borderColor;
if(col2.length==0) {alert("Bad Color!");}
步骤5:将颜色重新设置为空字符串,然后自己清理。
e.style.borderColor="";
分区:
<div id="mydiv" style="border-style:none; position:absolute; left:-9999px; top:-9999px;"></div>
现在,JavaScript函数:
function GoodColor(color)
{
var color2="";
var result=true;
var e=document.getElementById('mydiv');
e.style.borderColor="";
e.style.borderColor=color;
color2=e.style.borderColor;
if (color2.length==0){result=false;}
e.style.borderColor="";
return result;
}
在这种情况下,该函数将返回问题的是/否答案,另一个选择是使其返回有效的颜色值。您的原始颜色值,来自borderColor的值或一个空字符串代替无效的颜色。
如果要在HTML中使用它,请尝试直接使用此模式:
pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$"
喜欢
<input id="hex" type="text" pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" />
它将进行验证以匹配请求的格式。
function validColor(color){
var $div = $("<div>");
$div.css("border", "1px solid "+color);
return ($div.css("border-color")!="")
}
https://gist.github.com/dustinpoissant/22ce25c9e536bb2c5a2a363601ba261c
注意:这需要jQuery
这适用于所有颜色类型,而不仅仅是十六进制值。它还不会将不必要的元素附加到DOM树。
如果您需要一个函数来告诉您某种颜色是否有效,则最好让它提供一些有用的信息(该颜色的计算值),并在无效颜色时返回null。这是我使用兼容(Chrome54&MSIE11)函数的目的,可以获取任何格式的“颜色”的RGBA值-可以是“绿色”,“#FFF”,“#89abcd”或“ rgb” (0,0,128)”或“ rgba(0,128,255,0.5)”。
/* getRGBA:
Get the RGBA values of a color.
If input is not a color, returns NULL, else returns an array of 4 values:
red (0-255), green (0-255), blue (0-255), alpha (0-1)
*/
function getRGBA(value) {
// get/create a 0 pixel element at the end of the document, to use to test properties against the client browser
var e = document.getElementById('test_style_element');
if (e == null) {
e = document.createElement('span');
e.id = 'test_style_element';
e.style.width = 0;
e.style.height = 0;
e.style.borderWidth = 0;
document.body.appendChild(e);
}
// use the browser to get the computed value of the input
e.style.borderColor = '';
e.style.borderColor = value;
if (e.style.borderColor == '') return null;
var computedStyle = window.getComputedStyle(e);
var c
if (typeof computedStyle.borderBottomColor != 'undefined') {
// as always, MSIE has to make life difficult
c = window.getComputedStyle(e).borderBottomColor;
} else {
c = window.getComputedStyle(e).borderColor;
}
var numbersAndCommas = c.replace(new RegExp('[^0-9.,]+','g'),'');
var values = numbersAndCommas.split(',');
for (var i = 0; i < values.length; i++)
values[i] = Number(values[i]);
if (values.length == 3) values.push(1);
return values;
}
AARRGGBB格式,则最后一种颜色可能是有效的。