小编典典

在JavaScript中解析CSS颜色的最有效方法是什么?

css

给定一个有效的CSS颜色值的字符串:

  • fff

  • ffffff

  • 白色
  • rgb(255,255,255)

需要获取以下格式的数字数组:[R,G,B]

用JavaScript(假设使用主要的浏览器)最有效的方法是什么?


阅读 383

收藏
2020-05-16

共1个答案

小编典典

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的格式,甚至hsl/ hsla如果添加HSL2RGB转换功能。

最后,命名的颜色。

    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()为其计算样式的格式。取回它,然后读出来即可。

2020-05-16