从网上看了个案例,是实现颜色值转换的,就想着自己也写个。网上的案例链接找不到了,这里也就不贴了。
JavaScript颜色转换的核心就是进制间的转换。
rgba(0,0,0,.4)转换成#000000,就是Number.toString(16)
#ffffff转换成rgb(255,255,255),就是parseInt(String,16)
代码如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" Content="text/html; charset=utf-8;"> <title>JS-颜色值的转换</title> <meta name="author" content="rainna" /> <meta name="keywords" content="rainna's js lib" /> <meta name="description" content="js" /> <style> *{margin:0;padding:0;} body{background:#f0f0f0;} h2{margin:0 0 20px;} input{width:300px;height:24px;line-height:24px;} .m-box{width:900px;margin:0 auto;padding:20px;} </style> </head> <body> <div class="m-box"> <h2>RGB(A)颜色转换为HEX十六进制的颜色值</h2> <div class="box1"> <input type="text" id="colorIpt1" value="rgba(0,0,0,.4)"/> <a href="#" id="link1">转换</a> <input type="text" id="colorIpt2"/> </div> </div> <div class="m-box"> <div class="box1"> <input type="text" id="colorIpt3" value="#ffffff"/> <a href="#" id="link2">转换</a> <input type="text" id="colorIpt4"/> </div> </div> <script> var colorChange = { rgbToHex:function(val){ //RGB(A)颜色转换为HEX十六进制的颜色值 var r, g, b, a, regRgba = /rgba?((d{1,3}),(d{1,3}),(d{1,3})(,([.d]+))?)/, //判断rgb颜色值格式的正则表达式,如rgba(255,20,10,.54) rsa = val.replace(/s+/g,'').match(regRgba); if(!!rsa){ r = parseInt(rsa[1]).toString(16); r = r.length == 1 ? '0' + r : r; g = (+rsa[2]).toString(16); g = g.length == 1 ? '0' + g : g; b = (+rsa[3]).toString(16); b = b.length == 1 ? '0' + b : b; a = (+(rsa[5] ? rsa[5] : 1)) * 100; return {hex:'#' + r + g + b, alpha: Math.ceil(a)}; }else{ return {hex:val, alpha:100}; } }, hexToRgb:function(val){ //HEX十六进制颜色值转换为RGB(A)颜色值 var a,b,c; if((/^#/g).test(val)){ a = val.slice(1,3); b = val.slice(3,5); c = val.slice(5,7); return {rgba:'rgb(' + parseInt(a,16) + ',' + parseInt(b,16) + ',' + parseInt(c,16) + ')'}; }else{ return {rgba:'无效值:' + val}; } } }; link1.onclick = function(){ var obj = colorChange.rgbToHex(document.getElementById('colorIpt1').value); document.getElementById('colorIpt2').value = '颜色值:' + obj.hex + ',透明度:' + obj.alpha + '%'; }; link2.onclick = function(){ var obj = colorChange.hexToRgb(document.getElementById('colorIpt3').value); document.getElementById('colorIpt4').value = '颜色值:' + obj.rgba; }; </script> </body> </html>