RGB to hex and hex to RGB

前端 未结 30 2783
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  执念已碎
    2020-11-21 07:24

    Shorthand version that accepts a string:

    function rgbToHex(a){
      a=a.replace(/[^\d,]/g,"").split(","); 
      return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
    }
    
    document.write(rgbToHex("rgb(255,255,255)"));

    To check if it's not already hexadecimal

    function rgbToHex(a){
      if(~a.indexOf("#"))return a;
      a=a.replace(/[^\d,]/g,"").split(","); 
      return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
    }
    
    document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));

提交回复
热议问题