JS using a conversion between the 16-bit color values rgb

Two days before the work among encountered a small problem, the background color when you want to transfer the value passed to sixteen forms, but because of the differences between the different browsers, resulting in color rgb values ​​passed sometimes in the form of, Therefore, after the reference line of code to change a conversion method.

The first is the idea of ​​conversion, rgb is expressed in the three primary colors, after which the three numbers converted to two hexadecimal numbers are spliced, after adding # in front of the expression has become the method of 16.

How to extract three numbers of the three primary colors, more than one way, I used globally match is to find, acquire consecutive numbers through positive.

The decimal and hexadecimal conversion way is to use an array of query, the first 10 decimal numbers and divided by 16, the quotient and the remainder were an array of query, and then stitching.

Specific code as follows:

function RGBToHex (rgb) { 
    var regexp = / [0-9] {0,3} / G;  
    var Re = rgb.match (regexp); // regular expressions remove the excess portion of the digital rgb extraction 
   var hexColor = "#"; var hex = [ '0', '. 1', '2', '. 3', '. 4', '. 5', '. 6', '. 7', '. 8', '. 9' , 'A', 'B', 'C', 'D', 'E', 'F.' ];  
    for ( var I = 0; I <re.length; I ++ ) {
         var R & lt = null, C = Re [I], L = C; 
         var HEXAR = [];
         the while (C>16){  
              r = c % 16;  
              c = (c / 16) >> 0; 
              hexAr.push(hex[r]);  
         } hexAr.push(hex[c]);
         if(l < 16&&l != ""){        
             hexAr.push(0)
         }
       hexColor += hexAr.reverse().join(''); 
    }  
   //alert(hexColor)  
   return hexColor;  
} 

The code is not complicated, hoping to give the novice a little help, we learn, grow ~

Reproduced in: https: //www.cnblogs.com/xiao-yao/archive/2012/07/03/2574937.html

Guess you like

Origin blog.csdn.net/weixin_34185320/article/details/94442531