背景颜色十六进制到 JavaScript 变量

发布于 2024-07-15 03:23:08 字数 531 浏览 8 评论 0原文

我对 JavaScript 和 jQuery 有点陌生,现在我面临一个问题:

我需要将一些数据发布到 PHP,其中一位数据需要是 div X 的背景颜色十六进制。jQuery

有 css(" background-color") 函数,使用它我可以将背景的 RGB 值获取到 JavaScript 变量中。

CSS 函数似乎返回一个像 rgb(0, 70, 255) 这样的字符串。

我找不到任何方法来获取背景颜色的十六进制(即使它在 CSS 中设置为十六进制)。

所以看来我需要转换它。 我找到了一个将 RGB 转换为十六进制的函数,但需要使用三个不同的变量 r、g 和 b 来调用它。 所以我需要将字符串 rgb(x,xx,xxx) 解析为 var r=x; var g=xx; var b=xxx; 不知何故。

我尝试用 JavaScript 谷歌解析字符串,但我并没有真正理解正则表达式的东西。

有没有办法以十六进制形式获取 div 的背景颜色,或者可以将字符串转换为 3 个不同的变量?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

〆一缕阳光ご 2024-07-22 03:23:08

尝试一下:

var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.

var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

delete (parts[0]);
for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
} 
var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"

回答下面评论中的问题:

我正在尝试修改正则表达式以处理 rgb 和 rgba,具体取决于我得到的是哪一个。 有什么提示吗? 谢谢。

我不确定它在这个问题的上下文中是否有意义(因为你不能用十六进制表示 rgba 颜色),但我想可能还有其他用途。 无论如何,您可以将正则表达式更改为如下所示:

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/

示例输出:

var d = document.createElement('div');
d.style.backgroundColor = 'rgba( 255,  60, 50, 0)';

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0\.\d+))?\)$/.exec(d.style.backgroundColor);

// ["rgba(255, 60, 50, 0.33)", "255", "60", "50", "0.33"]

try this out:

var rgbString = "rgb(0, 70, 255)"; // get this in whatever way.

var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
// parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

delete (parts[0]);
for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
} 
var hexString ='#'+parts.join('').toUpperCase(); // "#0070FF"

In response to the question in the comments below:

I'm trying to modify the regex to handle both rgb and rgba depending which one I get. Any hints? Thanks.

I'm not exactly sure if it makes sense in the context of this question (since you can't represent an rgba color in hex), but I guess there could be other uses. Anyway, you could change the regex to be like this:

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/

Example output:

var d = document.createElement('div');
d.style.backgroundColor = 'rgba( 255,  60, 50, 0)';

/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(1|0\.\d+))?\)$/.exec(d.style.backgroundColor);

// ["rgba(255, 60, 50, 0.33)", "255", "60", "50", "0.33"]
何以笙箫默 2024-07-22 03:23:08

如果您有可用的 jQuery,这就是我刚刚提出的超紧凑版本。

var RGBtoHEX = function(color) {
  return "#"+$.map(color.match(/\b(\d+)\b/g),function(digit){
    return ('0' + parseInt(digit).toString(16)).slice(-2)
  }).join('');
};

If you have jQuery available, this is the super-compact version that I just came up with.

var RGBtoHEX = function(color) {
  return "#"+$.map(color.match(/\b(\d+)\b/g),function(digit){
    return ('0' + parseInt(digit).toString(16)).slice(-2)
  }).join('');
};
绝不放开 2024-07-22 03:23:08

您也可以使用 rgb 设置 CSS 颜色,如下所示:

background-color: rgb(0, 70, 255);

它是 有效的 CSS , 不用担心。


编辑:参见nickf答案 如果您确实需要的话,可以找到一种转换它的好方法。

You can set a CSS color using rgb also, such as this:

background-color: rgb(0, 70, 255);

It is valid CSS, don't worry.


Edit: See nickf answer for a nice way to convert it if you absolutely need to.

是伱的 2024-07-22 03:23:08

我不久前发现了另一个函数(R0bb13)。 它没有正则表达式,所以我不得不从 nickf 借用它才能使其正常工作。 我发布它只是因为它是一个有趣的方法,不使用 if 语句或循环来给出结果。 此外,此脚本返回带有 # 的十六进制值(我在使用的 Farbtastic 插件需要它)时间)

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

// call the function: rgb( "rgb(0, 70, 255)" );
// returns: #0046ff

注意:nickf 脚本的十六进制结果应该是 0046ff 而不是 0070ff,但没什么大不了的:P

更新,另一种更好替代方法:

function rgb2hex(rgb) {
 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]);
}

I found another function awhile back (by R0bb13). It doesn't have the regex, so I had to borrow it from nickf to make it work properly. I'm only posting it because it's an interesting method that doesn't use an if statement or a loop to give you a result. Also this script returns the hex value with a # (It was needed by the Farbtastic plugin I was using at the time)

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }
 return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

// call the function: rgb( "rgb(0, 70, 255)" );
// returns: #0046ff

Note: The hex result from nickf's script should be 0046ff and not 0070ff, but no big deal :P

Update, another better alternative method:

function rgb2hex(rgb) {
 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]);
}
不念旧人 2024-07-22 03:23:08

用 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;
};

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;
};
相思故 2024-07-22 03:23:08

这些解决方案在 Chrome 中将失败,因为它返回背景颜色的 rgba(x,x,x,x)。

编辑:这不一定是真的。 Chrome 仍然会使用 rgb() 设置背景,具体取决于您在做什么。 最有可能的是,只要没有应用 alpha 通道,Chrome 就会以 rgb 而不是 rgba 进行响应。

These solutions will fail in Chrome, as it returns an rgba(x,x,x,x) for background-color.

EDIT: This is not necessarily true. Chrome will still set backgrounds using rgb(), depending on what you are doing. Most likely as long as there is no alpha channel applied, Chrome will respond with rgb instead of rgba.

她如夕阳 2024-07-22 03:23:08

这个解决方案怎么样,函数 stringRGB2HEX 返回输入字符串的副本,其中所有出现的格式为“rgb(r,g,b)”的颜色均已替换为十六进制格式“#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;
   }

这个也可以转换复杂样式的 RGB 颜色,例如 background

像这样的 style.background 值: "none no-repeatscroll rgb(0, 0, 0)" 很容易转换为 "none no-repeatscroll# 000000” 只需执行 stringRGB2HEX(style.background)

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)

稚然 2024-07-22 03:23:08

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

一个 JavaScript 类,它接受字符串并尝试从中找出有效的颜色。 一些接受的输入例如:

* rgb(0, 23, 255)
* #336699
* ffee66
* fb0
* red
* darkblue
* cadet blue

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
や莫失莫忘 2024-07-22 03:23:08

我找到了这个解决方案 http://haacked.com/ archive/2009/12/29/convert-rgb-to-hex.aspx 我正在我的项目中使用它

I found this solution http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx and i am using it in my project

梦过后 2024-07-22 03:23:08

给你,这将允许您使用 $(selector).getHexBackgroundColor() 轻松返回十六进制值:

$.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]);
}

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]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文