Background-color hex to JavaScript variable

2019-01-03 14:30发布

I'm kind of new to JavaScript and jQuery and now I'm facing a problem:

I need to post some data to PHP and one bit of the data needs to be the background color hex of div X.

jQuery has the css("background-color") function and with it I can get RGB value of the background into a JavaScript variable.

The CSS function seems to return a string like this rgb(0, 70, 255).

I couldn't find any way to get hex of the background-color (even though it's set as hex in CSS).

So it seems like I need to convert it. I found a function for converting RGB to hex, but it needs to be called with three different variables, r, g and b. So I would need to parse the string rgb(x,xx,xxx) into var r=x; var g=xx; var b=xxx; somehow.

I tried to google parsing strings with JavaScript, but I didn't really understand the regular expressions thing.

Is there a way to get the background-color of div as hex, or can the string be converted into 3 different variables?

10条回答
混吃等死
2楼-- · 2019-01-03 15:13

How about this solution, function stringRGB2HEX returns a copy of the input string where all occurencies of colors in the format "rgb(r,g,b)" have been replaced by the hex format "#rrggbb".

   //function for private usage of the function below
   //(declaring this one in global scope should make it faster rather than 
   //declaraing it as temporary function inside stringRGB2HEX that need to be
   //instantieted at every call of stringRGB2HEX
   function _rgb2hex(rgb_string, r, g, b) 
   {
      //VERY IMPORTANT: by adding (1 << 24) we avoid 'rgb(0, 0, 0)' to be mistakenly converted into '#0'
      var rgb = (1 << 24) | (parseInt(r) << 16) | (parseInt(g) << 8) | parseInt(b); //same thing of: ( r + (256 * g) + (65536 * b) + 16777216)
      //toString(16) specify hex 16 radix, works only for numbers [source: http://msdn.microsoft.com/en-us/library/dwab3ed2(v=VS.85).aspx]   
      return '#' + rgb.toString(16).substr(1); //substr(1) because we have to remove the (1 << 24) added above
   }

   function stringRGB2HEX(string)
   {
      if(typeof string === 'string')
         string = string.replace(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/g, _rgb2hex);
      return string;
   }

This one converts also rgb colors in complex styles like background.

A style.background value like: "none no-repeat scroll rgb(0, 0, 0)" is easily converted into "none no-repeat scroll #000000" by simply doing stringRGB2HEX(style.background)

查看更多
够拽才男人
3楼-- · 2019-01-03 15:19

With JQuery..

var cssColorToHex = function(colorStr){
    var hex = '#';
    $.each(colorStr.substring(4).split(','), function(i, str){
        var h = ($.trim(str.replace(')',''))*1).toString(16);
        hex += (h.length == 1) ? "0" + h : h;
    });
    return hex;
};
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-03 15:19

http://www.phpied.com/rgb-color-parser-in-javascript/

A JavaScript class that accepts a string and tries to figure out a valid color out of it. Some accepted inputs are for example:

* rgb(0, 23, 255)
* #336699
* ffee66
* fb0
* red
* darkblue
* cadet blue
查看更多
孤傲高冷的网名
5楼-- · 2019-01-03 15:20

Here you go, this will allow you to use $(selector).getHexBackgroundColor() to return the hex value easily :

$.fn.getHexBackgroundColor = function() {
    var rgb = $(this).css('background-color');
    rgb = rgb.match(/^rgb\((\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]);
}
查看更多
登录 后发表回答