convert to 3-digit hex color code

后端 未结 4 576
[愿得一人]
[愿得一人] 2020-12-19 00:08

I\'ve been using 3-digit hex color values in CSS for a long time: #fff, #999, #069, etc. I can see how the repeating letters/numbers a

4条回答
  •  無奈伤痛
    2020-12-19 01:08

    function hexfix(str) {
      var v, w;
      v = parseInt(str, 16);	// in rrggbb
      if (str.length == 3) {
        // nybble colors - fix to hex colors
    	//  0x00000rgb              -> 0x000r0g0b
    	//  0x000r0g0b | 0x00r0g0b0 -> 0x00rrggbb
    	w = ((v & 0xF00) << 8) | ((v & 0x0F0) << 4) | (v & 0x00F);
    	v = w | (w << 4);
      }
      return v.toString(16).toUpperCase();
     }
    
    var hex1 = 'AABBCC',
        hex2 = 'ABC';
    
    document.body.appendChild(document.createTextNode(hex1+" becomes "+hexfix(hex1)+'.  '));
    document.body.appendChild(document.createTextNode(hex2+" becomes "+hexfix(hex2)+'.  '));

    Something like this.

提交回复
热议问题