我已经制作了一个快速的JSfiddle表格,可以将8位十六进制代码转换为CSS rgba值;)
基础很简单-将您提供的字符串分成两位数的一部分,并转换为alpha通道的百分比率和RGB通道的小数位。标记如下:
<form action=""> <select id="format"> <option value="rgba">RGBa: RRGGBBAA</option> <option value="argb">aRGB: AARRGGBB</option> </select> <input type="text" id="hex" value="#949494E8" /> <button>Convert</button></form><p id="rgba"></p>
逻辑:
// Remove hashvar hex = $('#hex').val().slice(1);// Split to four channelsvar c = hex.match(/.{1,2}/g);// Function: to decimals (for RGB)var d = function(v) { return parseInt(v, 16);};// Function: to percentage (for alpha), to 3 decimalsvar p = function(v) { return parseFloat(parseInt((parseInt(v, 16)/255)*1000)/1000);};// Check format: if it's argb, pop the alpha value from the end and move it to frontvar a, rgb=[];if($('#format').val() === 'argb') { c.push(c.shift());}// Convert array into rgba valuesa = p(c[3]);$.each(c.slice(0,3), function(i,v) { rgb.push(d(v));});转换的要点如下:
- 将十六进制RGB通道转换为十进制值。这是通过使用完成的
parseInt(hexValue, 16)
。 - 将十六进制的Alpha通道转换为百分比。只需将其转换为十进制值(请参见上文),然后将其相对值计算为255,即可完成此操作。



