javascript - 如何返回div背景颜色的十六进制值(没有jquery)?
问题描述
假设我有一个这样的 div
<div style="height:50px; width:50px; background-color:#ffffff" id="a1"></div>
我将在 JS 中做什么来获取字符串中的#ffffff?
解决方案
根据所使用的浏览器,从 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>
推荐阅读
- mysql - 在 SQL 中将资产相互关联
- json - 在 shell 脚本中使用来自 main while 的输入的嵌套 while 循环
- javascript - ES6 代理 - 是否可以在调用空对象之前捕获方法?
- ember.js - 弃用:ember-cli-babel 5.x 已被弃用。无法获得余烬工作
- c# - 远程服务器返回错误:(502) Bad Gateway。在 MVC 中
- raspberry-pi3 - 启动时的 net-snmp 说 - Raspberry pi 中的“打开指定端点时出错” - 杰西卡
- php - 我无法在 pdo 中绑定到日期
- django - pycharm 中导入模型的 Intellisense 问题
- php - 通过 PHP 的 CSV 重复第一个条目
- c# - 尝试上传文件时,发生 FileBufferingReadStream.ThrowIfDisposed() 错误