How to get hex color value rather than RGB value?

前端 未结 19 3153
猫巷女王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条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 23:23

    Most browsers seem to return the RGB value when using:

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

    Only I.E (only 6 tested so far) returns the Hex value.

    To avoid error messages in I.E, you could wrap the function in an if statement:

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

提交回复
热议问题