html背景颜⾊透明度hex,CSS背景颜⾊设置透明度的两种⽅法
(8位hex和rgba)
⽬录
⼀、 6位HEX转RGBA
⼆、8位HEX
在写⼩程序的时候,有个需求是按背景颜⾊
background-color要设透明度0.85,让背景图⽚
background-image透⼀点出来,⽽且
background-color的值是后端传过来的动态数据,背景颜⾊动态改变,UI同学给的数据全是6位HEX,需要我⾃⼰设置透明度。
设置透明度⾸先会想到⽤opacity,但 opacity 会把被设置的元素及其⼦元素同时设置为同⼀个透明度,我需要⼦元素不透明,opacity就不能⽤了。
接下来讲两个实际可⽤性⽐较⾼的⽅法,以下两种⽅法都在chrome和⼩程序上亲测可⽤:
⼀、 6位HEX转RGBA
rgba的alpha值可以设透明度⽽不影响⼦元素。但是UI同学给的⼏百个数据都是6位hex,所以需要我⾃⼰⼿动把6位hex格式转成rgb格式,再加上alpha值0.85写成rgba(x, x, x, 0.85)。
其实hex转rgb就是⼗进制转⼗六进制,最简单的办法就是⽤JS原⽣的parseInt() 函数帮我们做转换。以下是MDN⽂档对parseInt的说明:
parseInt(string, radix) 将⼀个字符串 string 转换为 radix 进制的整数, radix 为介于2-36之间的数。
如果 radix 是 undefined、0或未指定的,JavaScript会假定以下情况:
如果输⼊的 string以 "0x"或 “0x”(⼀个0,后⾯是⼩写或⼤写的X)开头,那么radix被假定为16,字符串的其余部分被解析为⼗六进制数。
如果输⼊的 string以 “0”(0)开头, radix被假定为8(⼋进制)或10(⼗进制)。具体选择哪⼀个radix取决于
实现。ECMAScript 5 澄清了应该使⽤ 10 (⼗进制),但不是所有的浏览器都⽀持。因此,在使⽤ parseInt 时,⼀定要指定⼀个 radix。
如果输⼊的 string 以任何其他值开头, radix 是 10 (⼗进制)。
根据说明,我们有两种⽅式hex转rgb,可以parseInt(hex.slice(x, x+2), 16); 也可以parseInt('0x'+hex.slice(x, x+2))。最后再设置0-1或者百分数的alpha值,就顺利转好rgba了,以下是完整代码:
// 颜⾊格式 hex 转 rgba
const hexToRgba = (bgColor) => {
let color = bgColor.slice(1); // 去掉'#'号
let rgba = [
parseInt('0x'+color.slice(0, 2)),
parseInt('0x'+color.slice(2, 4)),
parseInt('0x'+color.slice(4, 6)),
0.85
];
return 'rgba(' + String() + ')';
};
最后的String() 函数不带参数指定分隔号,会默认⽤逗号分隔,正好是我们想要的。
⼆、8位HEX
要不是这个需求,我还不知道CSS Color Module Level 4标准早在2014年就推出8位hex和4位hex来⽀持设置alpha值,以实现hex和rgba的互转。这个办法可⽐6位HEX转RGBA简洁多了,先来简单解释⼀下:
8位hex是在6位hex基础上加后两位来表⽰alpha值,00表⽰完全透明,ff表⽰完全不透明。
8 digits
The first 6 digits are interpreted identically to the 6-digit notation.
主页壁纸怎么设置The last pair of digits, interpreted as a hexadecimal number, specifies the alpha channel of the color, where ‘00’represents a fully transparent color and ‘ff’ represent a fully opaque color.
In other words, #0000ffcc represents the same color as rgb(0 0 100% / 80%) (a slightly-transparent blue).
同理,4位hex是在3位hex基础上加后⼀位来表⽰alpha值,0表⽰完全透明,f表⽰完全不透明。
4 digits
This is a shorter variant of the 8-digit notation, “expanded” in the same way as the 3-digit notation is. The first digit, interpreted as a hexadecimal number, specifies the red channel of the color, where 0 represents the minimum value and f represents the maximum. The next three digits represent the green, blue, and alpha channels, respectively.
⽐如以下三种写法表⽰的是同个颜⾊:
.element {
background: rgba(0, 255, 0, 0.53);// rgba
background: #0f08;//4位hex
background: #00ff0088;//8位hex
}
以下是摘⾃⽂章8-Digit Hex Codes?的alpha值的⼗进制和⼗六进制对照表:
Alpha %
Hex
Rgb 255
100%
FF
255
95%
F2
242
90%
E6
217 80% CC 204 75% BF 191 70% B3 179 65% A6 166 60% 99 153 55% 8C 140 50% 80 128 45% 73 115 40% 66 102 35% 59 89
25%
40
64
20%
33
51
15%
26
38
10%
1A
26
5%
0D
13
0%
00
根据以上表,我在6位HEX后⾯加上字符串D9就能轻松搞定背景颜⾊设置透明度85%的需求了~觉得有⽤的请点个赞,谢谢⼤家的观看~转载请带本⽂链接,谢谢!