在写微信小程序的时候,有个需求是按背景颜色 background-color要设透明度0.85,让背景图片 background-image透一点出来,而且 background-color的值是后端传过来的动态数据,背景颜色动态改变,UI同学给的数据全是6位HEX,需要我自己设置透明度。

设置透明度首先会想到用opacity,但 opacity 会把被设置的元素及其子元素同时设置为同一个透明度,我需要子元素不透明,opacity就不能用了。

接下来讲两个实际可用性比较高的方法,以下两种方法都在chrome和微信小程序上亲测可用:

一、 6位HEX转RGBA

rgbaalpha值可以设透明度而不影响子元素。但是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会假定以下情况:

  1. 如果输入的 string以 "0x"或 “0x”(一个0,后面是小写或大写的X)开头,那么radix被假定为16,字符串的其余部分被解析为十六进制数。
  2. 如果输入的 string以 “0”(0)开头, radix被假定为8(八进制)或10(十进制)。具体选择哪一个radix取决于实现。ECMAScript 5 澄清了应该使用 10 (十进制),但不是所有的浏览器都支持。因此,在使用 parseInt 时,一定要指定一个 radix。
  3. 如果输入的 string 以任何其他值开头, radix 是 10 (十进制)。

根据说明,我们有两种方式hexrgb,可以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(' + rgba.toString() + ')';
};

最后的Array.prototype.toString() 函数不带参数指定分隔号,会默认用逗号分隔,正好是我们想要的。

二、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 %HexRgb 255
100%FF255
95%F2242
90%E6230
85%D9217
80%CC204
75%BF191
70%B3179
65%A6166
60%99153
55%8C140
50%80128
45%73115
40%66102
35%5989
30%4D77
25%4064
20%3351
15%2638
10%1A26
5%0D13
0%000

根据以上表,我在6位HEX后面加上字符串D9就能轻松搞定背景颜色设置透明度85%的需求了~

觉得有用的请点个赞,谢谢大家的观看~转载请带本文链接,谢谢!

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐