How to get hex color value rather than RGB value?

前端 未结 19 3213
猫巷女王i
猫巷女王i 2020-11-21 23:06

Using the following jQuery will get the RGB value of an element\'s background color:

$(\'#selector\').css(\'backgroundColor\');

Is there a

19条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 23:18

    Same answer like @Jim F answer but ES6 syntax , so, less instructions :

    const rgb2hex = (rgb) => {
      if (rgb.search("rgb") === -1) return rgb;
      rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
      const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2);
      return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    };
    

提交回复
热议问题