- 字符串截取的方式
function hexToRgba(hex,opacity = 1){ if(hex != '' && hex.startsWith('#') && (hex.length == 4 || hex.length == 7)){ if(hex.length == 4){ let str = '#' for(let i = 1;i < hex.length;i++){ let item = hex[i] str += item.repeat(2) } hex = str } let r = parseInt('0x'+hex.slice(1,3)),g = parseInt('0x'+hex.slice(3,5)),b = parseInt('0x'+hex.slice(5)); return `rgba(${r},${g},${b},${opacity})` } return 'What You Want ?' }
- 正则匹配的方式
function hexToTgba(hex,opacity = 1){ if(hex != '' && hex.startsWith('#') && (hex.length == 4 || hex.length == 7)){ if(hex.length == 4){ let str = '#' for(let i = 1;i < hex.length;i++){ let item = hex[i] str += item.repeat(2) } hex = str } let reg = /[0-9a-fA-F]{2}/g; let match = hex.match(reg) match = match.map(item => { return parseInt(`0x${item}`) }) return `rgba(${match.toString()},${opacity})` } return 'What You Want ?' }
注:#abc => #aabbcc,而不是#abc => #abcabc