Home  >  Article  >  Web Front-end  >  Javascript realizes mutual conversion between hexadecimal color value (HEX) and RGB format_javascript skills

Javascript realizes mutual conversion between hexadecimal color value (HEX) and RGB format_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:43:411379browse

In daily development, conversion between color range values ​​in different formats is often used. A solution is given below.

Copy code The code is as follows:

//Regular expression for hexadecimal color value
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
/*Convert RGB color to hexadecimal*/
String.prototype.colorHex = function(){
var that = this;
If(/^(rgb|RGB)/.test(that)){
        var aColor = that.replace(/(?:(|)|rgb|RGB)*/g,"").split(",");
      var strHex = "#";
for(var i=0; i             var hex = Number(aColor).toString(16);
                if(hex === "0"){
Hex = hex;
            }
              strHex = hex;
}
If(strHex.length !== 7){
             strHex = that;                              }
         return strHex;
}else if(reg.test(that)){
      var aNum = that.replace(/#/,"").split("");
If(aNum.length === 6){
             return that;                                       }else if(aNum.length === 3){
            var numHex = "#";
for(var i=0; i               numHex = (aNum aNum);
            }
               return numHex;
}
}else{
         return that;                             }};
/*Convert hexadecimal color to RGB format*/
String.prototype.colorRgb = function(){
var sColor = this.toLowerCase();
If(sColor && reg.test(sColor)){
If(sColor.length === 4){
            var sColorNew = "#";
for(var i=1; i<4; i =1){
                    sColorNew = sColor.slice(i,i 1).concat(sColor.slice(i,i 1));                                                     }
            sColor = sColorNew;
}
//Processing six-digit color values
        var sColorChange = [];
for(var i=1; i<7; i =2){
             sColorChange.push(parseInt("0x" sColor.slice(i,i 2)));                                       }
          return "RGB(" sColorChange.join(",") ")";
}else{
         return sColor;                                                     }};


Use color conversion method:



Copy code

The code is as follows:

ar sRgb = "RGB(23, 245, 56)" , sHex = "#34538b";
var sHexColor = sRgb.colorHex();
var sRgbColor = sHex.colorRgb();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn