在CSS Color Module Level 4的标准中,可以使用8位hex和4位hex来支持设置alpha的值。
8位hex是在6位hex的基础上加上后两位来表示alpha值,00表示完全透明,ff表示完全不透明。同理4位hex和3位hex一样。
在此基础上,为针对在6位hex颜色的基础上添加透明度的需求,我们可以编写出以下方法。
/**
* @param {string} [color='#000'] 需要添加透明度的十六进制颜色
* @param {string} [opacity='0.5'] 透明度,在 0 - 1 之间
* @return {string} 添加了alpha值的8为hex
*/
function getHexOpacityColor(color = '#000', opacity) {
// 把alpha的值控制在 0 - 1 之间
let alpha = Math.max(opacity, 0);
alpha = Math.min(alpha, 1);
let c = color.replace(/\#/g, '').toUpperCase();
if (c.length === 3) {
let arr = c.split('');
c = '';
// 将3位hex字符补全至6位
for (let i = 0; i < arr.length; i++) {
c += (arr[i] + arr[i]);
}
}
let num = Math.round(255 * alpha); // 四舍五入
let str = num.toString(16).toUpperCase();
// 补全两位透明度
if (str.length === 1) {
str = '0' + str;
}
if (str.length === 0) {
str = '00';
}
return `#${c + str}`;
}