给定一串有效的 CSS 颜色值:
- #fff
- #ffffff
- 白色
- RGB(255, 255, 255)
我需要获取以下格式的数字数组:[R, G, B]
在 JavaScript 中执行此操作的最有效方法是什么(假设是主流浏览器)?
最佳答案
function parseColor(input) {
var m;
显然,数值比名称更容易解析。所以我们先做这些。
m = input.match(/^#([0-9a-f]{3})$/i)[1];
if( m) {
// in three-character format, each value is multiplied by 0x11 to give an
// even scale from 0x00 to 0xff
return [
parseInt(m.charAt(0),16)*0x11,
parseInt(m.charAt(1),16)*0x11,
parseInt(m.charAt(2),16)*0x11
];
}
就是一个。现在完整的六位数格式:
m = input.match(/^#([0-9a-f]{6})$/i)[1];
if( m) {
return [
parseInt(m.substr(0,2),16),
parseInt(m.substr(2,2),16),
parseInt(m.substr(4,2),16)
];
}
现在对于 rgb()
格式:
m = input.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
if( m) {
return [m[1],m[2],m[3]];
}
可选地,您还可以添加对 rgba
格式的支持,如果添加 HSL2RGB 转换功能,甚至可以添加对 hsl
/hsla
的支持。
最后,命名颜色。
return ({
"red":[255,0,0],
"yellow":[255,255,0],
// ... and so on. Yes, you have to define ALL the colour codes.
})[input];
并关闭函数:
}
实际上,我不知道我为什么要写那么多。我刚刚注意到你指定了“假设一个主要的浏览器”,我假设这也意味着“最新的”?如果是这样...
function parseColor(input) {
var div = document.createElement('div'), m;
div.style.color = input;
m = getComputedStyle(div).color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
if( m) return [m[1],m[2],m[3]];
else throw new Error("Colour "+input+" could not be parsed.");
}
最新的浏览器会将任何给定的颜色转换为其计算样式的 rgb()
格式。把它拿回来,读出来。
关于javascript - 在 JavaScript 中解析 CSS 颜色的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068240/