I trying to compare the styles of elements on my page. But one element dynamically changes it's text color to red, but represented as a rgb value. And the other element (to compare it with) uses #123456 values. Is there a converter somewhere that can take rgb and turn it into #number?
For exa开发者_JAVA百科mple:
#000 instead of rgb(0, 0, 0)
People always forget that rgb colors can be expressed as percentages, as well as integers.
function rgbToHex(rgb){
var i= 0, c, hex= '#',
rgb= String(rgb).match(/\d+(\.\d+)?%?/g);
while(i<3){
c= rgb[i++];
if(c.indexOf('%')!= -1){
c= Math.round(parseFloat(c)*2.55);
}
c= (+c).toString(16);
if(c.length== 1) c= '0'+c;
hex+= c;
}
return hex;
}
alert(rgbtohex('rgb(255,127,0)')+'\n'+
rgbtohex('rgb(100%,50%,0)'));
/* returned value:
#ff7f00
#ff7f00
*/
// also works with arrays- rgbToHex([100,200,60])
// returned value: #64c83c
function rgbToHex(R, G, B){
return toHex(R) + toHex(G) + toHex(B);
}
function toHex(n){
n = parseInt(n, 10);
if( isNaN(n) ){
return "00";
}
n = Math.max(0, Math.min(n,255));
return "0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16);
}
edited. courtesy of http://www.javascripter.net/faq/rgbtohex.htm
精彩评论