Convert Hex to RGBA

后端 未结 18 952
南方客
南方客 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:30

    @ElDoRado1239 has the right idea, but there's also a cleaner way:

    function hexToRGB(hex, alpha) {
        var r = parseInt(hex.slice(1, 3), 16),
            g = parseInt(hex.slice(3, 5), 16),
            b = parseInt(hex.slice(5, 7), 16);
    
        if (alpha) {
            return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
        } else {
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    }
    
    hexToRGB('#FF0000', 0.5);

提交回复
热议问题