最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Merge colors using javascript - Stack Overflow

programmeradmin1浏览0评论

Let say I have some element with background and foreground colors.
Let say there could be both colors specified in different formats (any that could be specified in style attribute) like background = 'white' or 'transparent', foreground = 'rgb(0, 0, 0)'.
What is simplest way to merge these colors using pure javascript to get result like rgb(128, 128, 128)?

Thanks.

Let say I have some element with background and foreground colors.
Let say there could be both colors specified in different formats (any that could be specified in style attribute) like background = 'white' or 'transparent', foreground = 'rgb(0, 0, 0)'.
What is simplest way to merge these colors using pure javascript to get result like rgb(128, 128, 128)?

Thanks.

Share Improve this question edited May 31, 2011 at 20:12 Mykhaylo Adamovych asked May 31, 2011 at 19:27 Mykhaylo AdamovychMykhaylo Adamovych 21k26 gold badges109 silver badges148 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

I believe setting opacity CSS attribute to half (0.5) of the element on the front will get you there.

Alternatively, if you are using jQuery and you really want to get this into JavaScript, you can get both colors with jQuery's .css(), which returns something like rgb(0,0,0), then make averages of each base color (red, green, blue) and set the resulting value to whatever you need with the same directive (.css()).

Did it help?

Just cuz i like writing plicated scripts....

<span style="background-color:black; color:#fff";>Hi</span>

JS:

function getColorVals(color) {
    color = color.replace("rgb", "").replace("(", "").replace(")", "");
    return color.split(",");
}
var span = document.getElementsByTagName("span")[0];
var color1 = window.getComputedStyle(span).backgroundColor; //window.getComputedStyle ensures getting back rgb
var color2 = window.getComputedStyle(span).color;
var color1Vals = getColorVals(color1);
var color2Vals = getColorVals(color2);
var newColorVal = "rgb(";
for (i = 0; i < 3; i++) {
    newColorVal += Math.round((Math.abs(color1Vals[i] - color2Vals[i]) / 2));
    if(i<2) newColorVal += ",";
} 
newColorVal += ")";
alert(newColorVal); 

...you could easily work the opacity in there as well.

EDIT:

popped in Math.round in the color val calculation to fix decimals and such.

You may want to look into rbgcolor.js. It "accepts a string and tries to figure out a valid color out of it". That is, you could simply look at the CSS color attribute on an element, feed it through this JS, and get the RGB values. Once you have the RGB values, simply take the average of each channel to create your new color.

You may have to do some finessing if the color of your element is inherited. e.g., if your element doesn't have a specified color property, check it's parent, all the way up the DOM.

发布评论

评论列表(0)

  1. 暂无评论