javascript 16进制颜色转RGB

白昼怎懂夜的黑 提交于 2020-03-12 02:03:05

 

效果如图:

javascript:

window.onload = function () {
    document.getElementById("change").onclick = function () {
        var color = document.getElementById("color_get").value;
        var _R,
            _G,
            _B;
 
        if (color.length == 4) {
            _R = parseInt(color.substr(1,1),16);
            _G = parseInt(color.substr(2,1),16);
            _B = parseInt(color.substr(3,1),16);
 
            document.getElementById("color_txt").innerHTML = "R(" + _R * _R + ")" + "," + "G(" + _G * _G + ")" + "," + "B(" + _B * _B + ")";
        }
        else if (color.length == 7) {
            _R = parseInt(color.substr(1,2),16);
            _G = parseInt(color.substr(3,2),16);
            _B = parseInt(color.substr(5,2),16);
 
            document.getElementById("color_txt").innerHTML = "R(" + _R + ")" + "," + "G(" + _G + ")" + "," + "B(" + _B + ")";
        }
        else {
            document.getElementById("color_txt").innerHTML = "请输入正确格式,例如:#FFFFFF";
        }
 
        document.getElementById("color_img").style.backgroundColor = color;
          
    }
}

css:

#color_img {
    width: 100px;
    height: 100px;
    border: 1px solid #e5e5e5;
}
 
#color_txt {
    color: #4d4d4d;
    font: 14px/24px Arial;
}

html:

<div id="color_img"></div>
<div id="color_txt"></div>
<input id="color_get" type="text"><input id="change" type="button" value="转换">

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!