What is the most efficient way to parse a CSS color in JavaScript?

后端 未结 9 1918
甜味超标
甜味超标 2020-12-06 04:36

Given a string of a valid CSS color value:

  • #fff
  • #ffffff
  • white
  • rgb(255, 255, 255)

Need to get an array of numbers of t

9条回答
  •  情话喂你
    2020-12-06 05:13

    Trying @Niet_the_Dark_Absol's answer with this beautiful getComputedStyle hack, I've been unable to make it work until appending to the DOM the created element (Chrome 69 and Firefox 75).

    As I also wanted to be able to handle the alpha channel value (transparency), I modified the Regex and returned result.

    Here is my function if it can be of any help for anyone:

    function colorToRgbParser(cssColor) {
      const div = document.createElement('div');
      div.id = 'for-computed-style';
    
      div.style.color = cssColor;
    
      // appending the created element to the DOM
      document.querySelector('body').appendChild(div);
    
      const match = getComputedStyle(div).color.match(/^rgba?\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d\.\d)\s*)?\)$/i);
    
      // removing element from the DOM
      document.querySelector('#for-computed-style').remove();
    
      if (match) {
        // match[0] is regex complete match (e.g. "rgb(0,0,0)"), not a regex capturing group
        let parsedColor = {
          r: match[1],
          g: match[2],
          b: match[3]
        };
        if (match[4]) { // if alpha channel is present
          parsedColor.a = match[4];
        }
        return parsedColor;
      } else {
        throw new Error(`Color ${cssColor} could not be parsed.`);
      }
    }
    

提交回复
热议问题