gpt4 book ai didi

css - 将 8 位十六进制颜色转换为 rgba 颜色?

转载 作者:技术小花猫 更新时间:2023-10-29 10:19:39 28 4
gpt4 key购买 nike

我在这个主题上发现的所有内容都只是将十六进制转换为 rgb,然后添加一个 1 的 alpha。我也想从十六进制数字中获得预期的 alpha。

#949494E8#DCDCDC8F 等颜色显然具有非 0 或 1 的 alpha 值。

最佳答案

我制作了一个快速的 JSfiddle 表单,允许您将 8 位十六进制代码转换为 CSS rgba 值;)

https://jsfiddle.net/teddyrised/g02s07n4/embedded/result/

基础相当简单 — 将您提供的字符串拆分为 2 位数字的部分,然后将 Alpha channel 转换为百分比,将 RGB channel 转换为小数。标记如下:

<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 hash
var hex = $('#hex').val().slice(1);

// Split to four channels
var 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 decimals
var 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 front
var a, rgb=[];
if($('#format').val() === 'argb') {
c.push(c.shift());
}

// Convert array into rgba values
a = p(c[3]);
$.each(c.slice(0,3), function(i,v) {
rgb.push(d(v));
});

转换要点如下:

  • 将十六进制的 RGB channel 转换为十进制值。这是通过使用 parseInt(hexValue, 16) 完成的。
  • 将十六进制的 alpha channel 转换为百分比。这是通过简单地将其转换为十进制值(见上一点),并将其相对值计算为 255 来完成的。

关于css - 将 8 位十六进制颜色转换为 rgba 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29100161/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com