Convert Hex to RGBA

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

    I liked the @AJFarkas answer and append the support for shortcut hex (#fff) to it

    function hexToRGB(hex, alpha) {
        if (!hex || [4, 7].indexOf(hex.length) === -1) {
            return; // throw new Error('Bad Hex');
        }
    
        hex = hex.substr(1);
        // if shortcuts (#F00) -> set to normal (#FF0000)
        if (hex.length === 3) { 
            hex = hex.split('').map(function(el){ 
                  return el + el + '';
                }).join('');
        }
    
        var r = parseInt(hex.slice(0, 2), 16),
            g = parseInt(hex.slice(2, 4), 16),
            b = parseInt(hex.slice(4, 6), 16);
    
        if (alpha !== undefined) {
            return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
        } else {
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    }
    
    document.write(hexToRGB('#FF0000', 0.5));
    document.write('
    '); document.write(hexToRGB('#F00', 0.4));

提交回复
热议问题