JS实现rgb与16进制颜色相互转换

1.rgb转16进制

function to16 (a) {//RGB(204,204,024)
  //十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  var that = a;
  if (/^(rgb|RGB)/.test(that)) {
    var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
    var strHex = "#";
    for (var i = 0; i < aColor.length; i++) {
    var hex = Number(aColor[i]).toString(16);
    if (hex === "0") {
    hex += hex;
  }
  strHex += hex;
  }
  if (strHex.length !== 7) {
    strHex = that;
  }
  return strHex;
  } else if (reg.test(that)) {
    var aNum = that.replace(/#/, "").split("");
    if (aNum.length === 6) {
      return that;
    } else if (aNum.length === 3) {
     var numHex = "#";
     for (var i = 0; i < aNum.length; i += 1) {
      numHex += (aNum[i] + aNum[i]);
    }
  return numHex;
}
} else {
return that;
}
}

2.16进制转rgb

function torgb(a) {//#ffffff
//十六进制颜色值的正则表达式
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
var sColor = a.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return "RGB(" + sColorChange.join(",") + ")";
} else {
return sColor;
}
}

JS实现rgb与16进制颜色相互转换,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。