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; } strHex += hex; } return strHex; } else { return String(color); } };