javascript实现十六进制颜色值(HEX)和RGB格式相互转换
在日常开发中,经常会用到不同格式的颜色域值之间的相互转换,以下给出一种解决方法。
//十六进制颜色值的正则表达式 varreg=/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; /*RGB颜色转换为16进制*/ String.prototype.colorHex=function(){ varthat=this; if(/^(rgb|RGB)/.test(that)){ varaColor=that.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(","); varstrHex="#"; for(vari=0;i<aColor.length;i++){ varhex=Number(aColor).toString(16); if(hex==="0"){ hex+=hex; } strHex+=hex; } if(strHex.length!==7){ strHex=that; } returnstrHex; }elseif(reg.test(that)){ varaNum=that.replace(/#/,"").split(""); if(aNum.length===6){ returnthat; }elseif(aNum.length===3){ varnumHex="#"; for(vari=0;i<aNum.length;i+=1){ numHex+=(aNum+aNum); } returnnumHex; } }else{ returnthat; }}; /*16进制颜色转为RGB格式*/ String.prototype.colorRgb=function(){ varsColor=this.toLowerCase(); if(sColor&®.test(sColor)){ if(sColor.length===4){ varsColorNew="#"; for(vari=1;i<4;i+=1){ sColorNew+=sColor.slice(i,i+1).concat(sColor.slice(i,i+1)); } sColor=sColorNew; } //处理六位的颜色值 varsColorChange=[]; for(vari=1;i<7;i+=2){ sColorChange.push(parseInt("0x"+sColor.slice(i,i+2))); } return"RGB("+sColorChange.join(",")+")"; }else{ returnsColor; }};
使用颜色转换方法:
arsRgb="RGB(23,245,56)",sHex="#34538b"; varsHexColor=sRgb.colorHex(); varsRgbColor=sHex.colorRgb();