开发者

Is there a way to convert word colors ("red", "blue", "green") into #123456 values?

I've been stuck on this fo开发者_JAVA百科r a while. I keep trying to compare colors for elements but even if the colors are the same, the values representing them are not. One is #000 and the other is "black". How do I take "black" and turn it into #000. With that said, how do I take any word color and turn it into a number?


I've seen this question asked in the past and i think you can find a good script here.

The script is from a great programmer in javasscript and, well, actually he does a word look up, there is no other way to do it i think.


I'm not sure it is possible x-browser without a predefined list of colours. It's simple enough in browsers supporting window.getComputedStyle():

function getColorFromName(name) {
    var rgb,
        tmp = document.body.appendChild(document.createElement("div"));

    tmp.style.backgroundColor = name;
    rgb = window.getComputedStyle(div, null);
    //-> returns format "rgb(r, g, b)", which can be parsed and converted to hex
}

For browsers not supporting this, the only option you have is to use an object map and define the values yourself:

var colours = {
    aliceblue:      "#F0F8FF",
    antiquewhite:   "#FAEBD7",
    aqua:           "#00FFFF"
    //...etc
}

// and lookup
alert(colours[document.getElementById("div").style.backgroundColor.toLowerCase()]);

A full list of colours supported in CSS3 is available from http://www.w3.org/TR/css3-color/#svg-color.

Of course, the downside to the list method is that lists need to be maintained if the specification changes, so you might want to incorporate both methods - ie if getComputedStyle() is available, use it else fall back to the list. This ensures compatibility for both older browsers and newer browsers without ever needing to update the list.


Since you are using javascript you can use a "javaScript associative array" and have the assosiation "colorName <-> colorCode" you need.

You can find all the official color names here: http://www.w3schools.com/cssref/css_colornames.asp

here is some code:

var colors= new Array();
colors["black"] = "#000";
colors["AliceBlue"] = "#F0F8FF";
colors["AntiqueWhite"] = "#FAEBD7";

var mycolor = 'black'
alert('the code of '+mycolor +' is:'+colors[mycolor]);


If you set a CSS color property to your color string and then get the property back, most (at least some) modern browsers will give you a "normalized" color string. Firefox seems to like the "rgb(n, n, n)" notation.

edit — @Andy E notes that this doesn't work in too many browsers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜