自动将格式从HEX转换为RGB或将RGB转换为HEX

时间:2019-02-13 02:12:54

标签: javascript

编写一个将HEX转换为RGB的函数。

然后使该函数自动提取格式

这样,如果您输入十六进制颜色格式,它将返回RGB

,如果您输入RGB颜色格式,它将返回十六进制。

E.G。:

输入“#0033ff”输出rgb(0,15,255)

输入(0,15,255)输出“#0033ff”

尝试了以下功能来创建结果:

   function rgbToHexAndHextorgb(input1, input2, input3) {
    if(!input2){
	    //HEX
	    let hex = input1;
	     var shorthandRegex = input1;
         input1 = input1.replace(shorthandRegex, function(m, r, g, b) {
          return r + r + g + g + b + b;
        });

    var result = [];
    result.push(input1[2]+input1[3]);
    result.push(input1[4]+input1[5]);
    result.push(input1[6]+input1[7]);

    return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
} : null;
}
else
	{
     //RGB
   let r = input1;
   let g = input2;
   let b = input3;
   const componentToHex=(c)=>{
	   var hex2 = c.toString(16);
       return hex2.length == 1 ? "0" + hex2 : hex2;
   }
   return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
	
   }
 }
   rgbToHexAndHextorgb(0, 51, 255) ;//"#0033ff"
   rgbToHexAndHextorgb("#0033ff");//(0,51,255)

1 个答案:

答案 0 :(得分:-1)

您可以立即准备带有3个参数的函数。

function rgbToHexAndHextorgb(input1, input2, input3) {
    if(!input2) {
        // HEX
        console.log('hex');
        let hex = input1;
    }
    else {
        // RGB
        console.log('rgb')
        let red = input1;
        let green = input2;
        let blue = input3;
    }
}

// Testing
rgbToHexAndHextorgb(1,2,3)
rgbToHexAndHextorgb('#000000')