首页 > 解决方案 > 如何返回div背景颜色的十六进制值(没有jquery)?

问题描述

假设我有一个这样的 div

<div style="height:50px; width:50px; background-color:#ffffff" id="a1"></div>

我将在 JS 中做什么来获取字符串中的#ffffff?

标签: javascripthtmlcss

解决方案


根据所使用的浏览器,从 DOM 元素中检索的颜色将返回为 RGB 值,除非直接使用 Javascript 指定。

例如,使用您的示例代码,我们可以div像这样使用 JS 应用背景颜色:

//get the div by id
var div = document.getElementById('a1');
//apply divs background color
var divBgColor = div.style.backgroundColor = '#ffffff';

如果您console.log(divBgColor);在使用上面的代码指定背景颜色后,它将#ffffff按照您的预期返回一个十六进制值。

但是,如果您的元素中已经声明了背景颜色并且您想要检索它,您将不得不做更多的事情。

同样,使用您的示例,我们可以获得这样的背景颜色:

var divBgColor = document.getElementById('a1').style.backgroundColor;

如果您console.log(divBgColor);现在,它将返回一个字符串rgb(255, 255, 255),但是,由于您正在寻找十六进制值,我们可以运行一个函数将 RGB 值转换为十六进制。

    function convertRgb(rgb) {
  // This will choose the correct separator, if there is a "," in your value it will use a comma, otherwise, a separator will not be used.
  var separator = rgb.indexOf(",") > -1 ? "," : " ";


  // This will convert "rgb(r,g,b)" into [r,g,b] so we can use the "+" to convert them back to numbers before using toString 
  rgb = rgb.substr(4).split(")")[0].split(separator);

  // Here we will convert the decimal values to hexadecimal using toString(16)
  var r = (+rgb[0]).toString(16),
    g = (+rgb[1]).toString(16),
    b = (+rgb[2]).toString(16);

  if (r.length == 1)
    r = "0" + r;
  if (g.length == 1)
    g = "0" + g;
  if (b.length == 1)
    b = "0" + b;

  // The return value is a concatenation of "#" plus the rgb values which will give you your hex
  return "#" + r + g + b;
}

现在您可以divBgColor像这样调用该函数,convertRgb(divBgColor)它将输出您的十六进制值。

运行下面的代码片段以查看它的实际效果。

var divBgColor = document.getElementById('a1').style.backgroundColor;

function convertRgb(rgb) {
  // This will choose the correct separator, if there is a "," in your value it will use a comma, otherwise, a separator will not be used.
  var separator = rgb.indexOf(",") > -1 ? "," : " ";


  // This will convert "rgb(r,g,b)" into [r,g,b] so we can use the "+" to convert them back to numbers before using toString 
  rgb = rgb.substr(4).split(")")[0].split(separator);

  // Here we will convert the decimal values to hexadecimal using toString(16)
  var r = (+rgb[0]).toString(16),
    g = (+rgb[1]).toString(16),
    b = (+rgb[2]).toString(16);

  if (r.length == 1)
    r = "0" + r;
  if (g.length == 1)
    g = "0" + g;
  if (b.length == 1)
    b = "0" + b;

  // The return value is a concatenation of "#" plus the rgb values which will give you your hex
  return "#" + r + g + b;
}

console.log(convertRgb(divBgColor))
<div style="height:50px; width:50px; background-color:#ffffff" id="a1"></div>


推荐阅读