Convert Hex to RGBA

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

    Here's an ES2015+ version that's a little more defensive and handles the shorthand 3-digit syntax.

    /*
     * Takes a 3 or 6-digit hex color code, and an optional 0-255 numeric alpha value
     */
    function hexToRGB(hex, alpha) {
      if (typeof hex !== 'string' || hex[0] !== '#') return null; // or return 'transparent'
    
      const stringValues = (hex.length === 4)
            ? [hex.slice(1, 2), hex.slice(2, 3), hex.slice(3, 4)].map(n => `${n}${n}`)
            : [hex.slice(1, 3), hex.slice(3, 5), hex.slice(5, 7)];
      const intValues = stringValues.map(n => parseInt(n, 16));
    
      return (typeof alpha === 'number')
        ? `rgba(${intValues.join(', ')}, ${alpha})`
        : `rgb(${intValues.join(', ')})`;
    }
    

提交回复
热议问题