Convert Hex to RGBA

后端 未结 18 950
南方客
南方客 2020-12-04 11:36

My fiddle - http://jsbin.com/pitu/1/edit

I wanted to try an easy hex to rgba conversion. Ever browser I\'ve used renders colors using rgb as default so when using th

18条回答
  •  无人及你
    2020-12-04 12:17

    //If you write your own code, remember hex color shortcuts (eg., #fff, #000)
    
    function hexToRgbA(hex){
        var c;
        if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
            c= hex.substring(1).split('');
            if(c.length== 3){
                c= [c[0], c[0], c[1], c[1], c[2], c[2]];
            }
            c= '0x'+c.join('');
            return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
        }
        throw new Error('Bad Hex');
    }
    
    hexToRgbA('#fbafff')
    
    /*  returned value: (String)
    rgba(251,175,255,1)
    */
    

提交回复
热议问题