How to get hex color value rather than RGB value?

前端 未结 19 3210
猫巷女王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:33

    Here is a version that also checks for transparent, I needed this since my object was to insert the result into a style attribute, where the transparent version of a hex color is actually the word "transparent"..

    function rgb2hex(rgb) {
         if (  rgb.search("rgb") == -1 ) {
              return rgb;
         }
         else if ( rgb == 'rgba(0, 0, 0, 0)' ) {
             return 'transparent';
         }
         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]); 
         }
    }
    

提交回复
热议问题