Last active
June 27, 2021 03:15
-
-
Save ifeiwu/9e4b4516369da59d0a474168878f1869 to your computer and use it in GitHub Desktop.
颜色RGB转HEX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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