JS技巧:轻松将十六进制颜色转换为rgb和rgba格式
最编程
2024-01-13 08:29:02
...
JS - 将十六进制的颜色值转成rgb、rgba格式
/**hex -> rgb
* @param {Object} hex
*/
export function hexToRgb(hex) {
return 'rgb(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5))
+ ',' + parseInt('0x' + hex.slice(5, 7)) + ')';
}
/**hex -> rgba
* @param {Object} hex
* @param {Object} opacity
*/
export function hexToRgba(hex, opacity) {
return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ','
+ parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')';
}
打印输入
var sHex = '#fffff';
console.log('十六进制格式:', sHex);
console.log('RGB格式:', hexToRgb(sHex));
console.log('RGBA格式:', hexToRgba(sHex, 0.5));