开发者

Merge colors using javascript

开发者 https://www.devze.com 2023-03-09 07:55 出处:网络
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) lik

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.


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 complicated 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

精彩评论

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