【问题标题】: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);
}

【讨论】:

    猜你喜欢
    • 2015-11-22
    • 2019-02-08
    • 2012-02-06
    • 1970-01-01
    • 2018-06-16
    • 2021-01-07
    • 1970-01-01
    • 2011-04-17
    • 2014-03-01
    相关资源
    最近更新 更多