wkiwi的博客

徒手撸一个颜色16进制与rgba相互转换

发布时间:12个月前热度: 224 ℃评论数:

在开发过程中经常收到UI给的UI标注图,但经常会遇到rgba与16进制颜色的转换每次还要打开PS或其他颜色工具转换颜色,特别麻烦,索性直接徒手撸一个离线颜色转换小网页,开箱即用!


直通车

下方是css,html,javaScript源码


html


<h2>16进制转rgba</h2> <div class="line">

<input type="text" placeholder="请输入16进制例如:#ffffff" id="input1"><span id="change1" class="change-btn">转换</span><input type="text" id="input2">
</div>
<h2>rgba转16进制</h2>
<div class="line">
<input type="text" placeholder="请输入rgba例如:rgba(255,255,255,1)" id="input3"><span id="change2" class="change-btn">转换</span><input type="text" id="input4">
</div>
<footer>BY:wkiwi</footer>



style


body{

text-align: center;

}
h2{
margin: 50px 0;
}
input{
width: 220px;
height: 50px;
padding: 0 20px;
}
.change-btn{
display:inline-block;
height:50px;
line-height: 50px;
text-align: center;
width:100px;
margin: 0 30px;
background:#8e14fd;
border-radius: 10px;
color: #ffffff;
}
footer{
position: absolute;
bottom: 0;
width:100%;
text-align: center;
}


js

// rgba转16进制:
function RGBToHex(rgb){ 
   var regexp = /[0-9]{0,3}/g;  
   var re = rgb.match(regexp);//利用正则表达式去掉多余的部分,将rgb中的数字提取
   var hexColor = "#"; var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];  
   for (var i = 0; i < re.length; i++) {
        var r = null, c = re[i], l = c; 
        var hexAr = [];
        while (c > 16){  
              r = c % 16;  
              c = (c / 16) >> 0; 
              hexAr.push(hex[r]);  
         } hexAr.push(hex[c]);
         if(l < 16&&l != ""){        
             hexAr.push(0)
         }
       hexColor += hexAr.reverse().join(''); 
    }  
   //alert(hexColor)  
   return hexColor;  
} 
//16进制转rgba
function HexToRGB(hex){
  var util = {
    cutHex: function (hex) {
        return hex.charAt(0) == "#" ? hex.substring(1, 7) : hex;
    },
    hexToR: function (hex) {
        return parseInt((util.cutHex(hex)).substring(0, 2), 16)
    },
    hexToG: function (hex) {
        return parseInt((util.cutHex(hex)).substring(2, 4), 16)
    },
    hexToB: function (hex) {
        return parseInt((util.cutHex(hex)).substring(4, 6), 16)
    },
    hexToRgba: function (hex) {
        return 'rgba('+util.hexToR(hex)+','+util.hexToG(hex)+','+util.hexToB(hex)+',1)';
    }
  };
  return util.hexToRgba(hex)
}

window.onload=function(){
    let change1 = document.getElementById('change1');
    let change2 = document.getElementById('change2');
    change1.onclick= function(){
      let val = document.getElementById('input1').value;
      document.getElementById('input2').value = HexToRGB(val)
    }
    change2.onclick= function(){
      let val = document.getElementById('input3').value;
      document.getElementById('input4').value = RGBToHex(val)
    }
}

rgba,颜色,16进制,16进制颜色与rgba相互转换

手机扫码访问