现在我得到一个包含名为' Clear'的颜色的对象。我想将它设置为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;
}
答案 0 :(得分:0)
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);
}