栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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(/^rgbs*(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 pres.    })[input];

并关闭功能:

}

其实,我不知道为什么要麻烦写这些。我刚刚注意到您指定了“假设使用主要的浏览器”,我想这也意味着“最新”吗?如果是这样的话…

function parseColor(input) {    var div = document.createElement('div'), m;    div.style.color = input;    m = getComputedStyle(div).color.match(/^rgbs*(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()
为其计算样式的格式。取回它,然后读出来即可。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/514753.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号