js 实现颜色值格式转换 rgb和十六进制的转换
参考:mossbaoo~
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>color拾取器</title> </head> <body> <div>社会主义接班人</div> <input type="color" id="color1"> <input type="color" id="color2"> </body> <script type="text/javascript" charset="utf-8"> /** * 以prototype原型的方式,给string字符串类型添加方法,用于实现颜色值格式的转换。 * * RGB转换为16进制 * * 使用方式: * "rgb(255,255,255)".colorHex(); // #ffffff */ String.prototype.colorHex = function() { // RGB颜色值的正则 var reg = /^(rgb|RGB)/; var color = this; if (reg.test(color)) { var strHex = "#"; // 把RGB的3个数值变成数组 var colorArr = color.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(","); // 转成16进制 for (var i = 0; i < colorArr.length; i++) { var hex = Number(colorArr[i]).toString(16); if (hex === "0") { hex += hex; }
hex = hex.length == 1?\'0\'+hex:hex; strHex += hex; } return strHex; } else { return String(color); } }; /** * 16进制转换为RGB * * 使用方式: * "#fff".colorRgb(); // rgb(255,255,255) * "#ffffff".colorRgb(); // rgb(255,255,255) */ String.prototype.colorRgb = function() { // 16进制颜色值的正则 var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 把颜色值变成小写 var color = this.toLowerCase(); if (reg.test(color)) { // 如果只有三位的值,需变成六位,如:#fff => #ffffff if (color.length === 4) { var colorNew = "#"; for (var i = 1; i < 4; i += 1) { colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1)); } color = colorNew; } // 处理六位的颜色值,转为RGB var colorChange = []; for (var i = 1; i < 7; i += 2) { colorChange.push(parseInt("0x" + color.slice(i, i + 2))); } return "RGB(" + colorChange.join(",") + ")"; } else { return color; } }; /** ========== 测试分割线 测试分割线 测试分割线 测试分割线 ========== */ var colorsHex = "#ff8080"; var colorsRgb = "rgb(255, 128, 128)" var colors = document.querySelector("#color1").value; console.log(colors); document.querySelector("#color1").onchange = function() { // document.getElementById(\'color1\').click(); // 必须添加触发click事件否则不能通过点击确定按钮触发更改颜色 document.body.style.color = this.value; var bodyColor = document.body.style.color; document.querySelector("#color2").value = bodyColor.colorHex(); console.log(bodyColor); console.log(bodyColor.colorHex()); console.log(document.body.style.color.colorHex()); } </script> </html>
hex = hex.length == 1 ? \'0\' + hex : hex;