#FFF转换为rgba(255,255,255,1)

  • 字符串截取的方式
function hexToRgba(hex = '#fff',opacity = 1){
    if(hex != '' && hex.startsWith('#') && (hex.length == 4 || hex.length == 7)){
        if(hex.length == 4){
           let [s, r, g ,b] = hex
            hex = `${s}${r}${r}${g}${g}${b}${b}`
        }
        let r = parseInt(hex.slice(1,3),16),g = parseInt(hex.slice(3,5),16),b = parseInt(hex.slice(5),16);
        return `rgba(${r},${g},${b},${opacity})`
    }
    return 'What You Want ?'
} 
  • 正则匹配的方式
function hexToRgba(hex,opacity = 1){
    if(hex != '' && hex.startsWith('#') && (hex.length == 4 || hex.length == 7)){
        if(hex.length == 4){
            let [s, r, g ,b] = hex
            hex = `${s}${r}${r}${g}${g}${b}${b}`
        }
        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 我这个是对的 

posted @ 2020-05-26 12:38  671_MrSix  阅读(2825)  评论(0编辑  收藏  举报