Skip to content

Instantly share code, notes, and snippets.

@ifeiwu
Last active June 27, 2021 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifeiwu/9e4b4516369da59d0a474168878f1869 to your computer and use it in GitHub Desktop.
Save ifeiwu/9e4b4516369da59d0a474168878f1869 to your computer and use it in GitHub Desktop.
颜色RGB转HEX
String.prototype.colorHex = function() {
var that = this;
//十六进制颜色值的正则表达式
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
// 如果是rgb颜色表示
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.length < 2) {
hex = '0' + 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;
}
}
return that;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment