【问题标题】:How to set color 'Clear' to RGB or HEX?如何将颜色“清除”设置为 RGB 或 HEX?
【发布时间】:2016-07-12 23:31:13
【问题描述】:
现在我得到一个包含名为“清除”的颜色的对象。我想将它设置为 RGB 值,并且我使用了一个函数来执行此操作,但它返回我'rgb(51、51、51)',而在角度 chorme 图表中它将它解析为'#3366cc'。我该怎么做在不使用其他 js 库的情况下获取 rgb 值?
-
function(){
var div = document.createElement('div');
var rgbColor;
div.style.color = 'Clear';
document.body.appendChild(div);
rgbColor = window.getComputedStyle(div).color
div.remove();
return rgbColor;
}
【问题讨论】:
标签:
javascript
css
colors
hex
rgb
【解决方案1】:
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
function getColor(){
var r = 0;
var g = 0;
var b = 0;
var rgbColor;
var div = document.createElement('div');
div.style.color = 'Clear';
document.body.appendChild(div);
rgbColor = window.getComputedStyle(div).color
var matches = div.style.color.match(/^rgb\((\d+), (\d+), (\d+)\)$/);
if (matches) {
r = parseInt(matches[1]);
g = parseInt(matches[2]);
b = parseInt(matches[3]);
}
div.remove();
return rgbToHex(r, g, b);
}