从颜色词获取颜色代码

4

我想编写一个JavaScript程序,以获取CSS中定义的颜色单词的RGB颜色。

例如,如果我输入red,我想要输出rgb(255, 0, 0)。 我还想将rgb(255, 0, 0)转换为red

在JavaScript中是否有方法可以实现这个目的?


2
不是我点的踩。rgb(51, 51, 51) 是(有点暗的)灰色。红色是255,0,0。 - zkanoca
3
最简单可靠的方法肯定是使用映射对象将所有颜色映射到所有RGB值。 - Christoph
@Christoph 是的,但我想以编程方式实现它。 - Alexis
1
这是另一半:https://dev59.com/0Wox5IYBdhLWcg3wazmR(标记为重复) - Salman A
@SalmanA 注意,颜色分类器列出了浏览器中不可用的颜色!Web 颜色为:http://dev.w3.org/csswg/css-color/#svg-color,而“非 Web”有更多的颜色可用:http://en.wikipedia.org/wiki/List_of_colors。 - Christoph
显示剩余3条评论
3个回答

4
这在编程方面不容易实现,因为浏览器的行为不同。你不能确定它们返回原始值(例如你的单词)还是计算后的十六进制或RGB值。(不过使用getComputedStyle()是可能的!)
在任何情况下,你都无法获取rgb/hex/hsl值的颜色单词。(至少我不知道有这种可能性。)
“最简单”、可靠的方法是创建一个映射对象,其中包含所有颜色单词及其相应的值。你可以在这里找到列表:

http://dev.w3.org/csswg/css-color/#svg-color

var word2value = {
       red: {"hex":"#FF0000","rgb":"255,0,0"},
       /* ... all other values */
}

var value2word = {
       "FF0000" : "red",
       "255,0,0": "red"
}

注意,你需要使用方括号访问: value2word["255,0,0"]

这绝对是最可靠的方法。+1,因为它支持双向。 - Moritz Roessler

2
您可以:
  • 使用JavaScript创建一个新元素。
  • 将其背景颜色设置为输入值。
  • 将其附加到body中。
  • 获取它的window.getComputedStyle 注意:兼容性问题
  • 返回等效的backgroundColor

function getRGB(v) {
    var el = document.createElement("div");
    el.style["background-color"] = v;
    document.body.appendChild(el);

    var style = window.getComputedStyle(el);

    var color = style["backgroundColor"];

    document.body.removeChild(el);
    return color;

}

getRGB ("red") //"rgb(255, 0, 0)"

但请注意:正如Cristoph所说,你不能确定总是得到正确的值。 虽然在Chrome上对我来说效果相当不错。
但我认为你不能像Cristoph建议的那样没有Map就把它反过来获取。
JSBin上的演示。
更新。
这是一个带有完整映射的函数,它返回包含颜色的十六进制、命名和RGB表示的Color对象。
function getColor (r,g,b) {

var colors = {TooBigToPostHere:...}     //see the JSBin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
function rgbToHex(r, g, b) {
     var hex = "#";
     for (var i = 0; i < 3; i++) {
         var _hex = arguments[i].toString(16);
         while (_hex.length < 2) _hex = "0" + _hex;
         hex += _hex
     }
     return hex.toUpperCase();
 }
 if (typeof r === "string")  r = r["to"+(!!~r.indexOf("#")?"Upper":"Lower")+"Case"]();   
 if (r in colors) return colors[r]
 else if (r !== undefined && g !== undefined && b !== undefined) {
     var hex = rgbToHex(r, g, b);
     if (hex in colors) return colors[hex]
     else return {
             rgb: [r, g, b],
             hex: hex,
             name: null
     }
 } else {
     throw new SyntaxError("Invalid Arguments");
 }

}

这会产生如下输出:
console.log ( getColor (245,245,245)) //{"hex": "#F5F5F5", "name": "whitesmoke", "rgb": [245, 245, 245]}
console.log ( getColor ("#EE82EE")); //{"hex": "#EE82EE", "name": "violet", "rgb": [238, 130, 238]}
console.log ( getColor ("red")); //{"hex": "#FF0000", "name": "red", "rgb": [255, 0, 0]}

还有一个关于JSBin的演示
注意:colors 包含了扩展颜色关键词的完整列表

这是我用来爬取上述颜色表格的代码

var colors = {};
[].forEach.call(document.querySelectorAll (".colortable tr"), function (e,i) {
if ( i > 0 ) {
 var hex = e.children[3].innerText;
 colors[hex] = {};
 colors[hex].hex = hex;
 colors[hex].name = e.children[2].innerText;
 colors[hex].rgb = e.children[4].innerText.split(",");
 colors[hex].rgb.map(function (a,b,c) {c[b] = +a})
 colors[colors[hex].name] = colors[hex];
 }
});

2
我认为这是您想要的内容:
Text:
<input type="text" id="ctext" />
<br>RGB:
<input type="text" id="crgb" />
<br>
<button onclick="doMagic();">Magic</button>
<div id="output" style="display:none"></div>
<script>
    function doMagic() {
        $('#output').html('<p id=test style=\'color:' + $('#ctext').val() + ';\'>sometext</p>');
        $('#crgb').val($('#test').css("color"));
    }
</script>

fiddle 上查看。

我认为它的功能非常棒!


1
另一方面呢? - Christoph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接