首页 > 解决方案 > javascript中的十六进制到rgb转换器

问题描述

我正在尝试制作一个简单的 rgb 到十六进制转换器,但我一直被 Javascript 卡住,我做错了什么?在 html 部分,我制作了一个表单,在提交时调用 convert() 函数。

function convert() {
    r = parseInt(document.getElementById('r').value);
    g = parseInt(document.getElementById('g').value);
    b = parseInt(document.getElementById('b').value);

    rgb(r, g, b);
    function rgb(r, g, b){
        res = ColorToHex(r) + ColorToHex(g) + ColorToHex(b);
        function ColorToHex(color) {
            if (color > 255) return "FF";
            else if (color < 0) return "00";
            else color.toString(16).padStart(2, "0").toUpperCase();
          }
    }
    document.getElementById('result').innerHTML = res;    
    return false;
}

标签: javascripthtmlhexrgb

解决方案


这从 RGB 返回十六进制

console.log(convert('255','18', '50'));

function convert(r, g, b) {
    r = parseInt(r); g = parseInt(g); b = parseInt(b);
    res = r.toString(16) + g.toString(16) + b.toString(16);
    res = res.toUpperCase();
    return res;
}

推荐阅读