Bei der täglichen Entwicklung wird häufig die gegenseitige Umwandlung zwischen Farbdomänenwerten in verschiedenen Formaten verwendet. Hier ist eine Lösung.
Die Codekopie lautet wie folgt:
// regelmäßiger Ausdruck des hexadezimalen Farbwerts
var reg = /^#([0-9a-fa-f] {3} | [0-9a-fa-f] {6}) $ /;
/*RGB -Farbkonvertierung in Hexadezimal*/
String.prototype.colorhex = function () {
var das = dies;
if (/^(rgb | rgb)/. test (das)) {
var acolor = that.replace (/(?:/(|/) | rgb | rgb)*/g, ""). split (",");
var strhex = "#";
für (var i = 0; i <acolor.length; i ++) {
var hex = nummer (acolor) .tostring (16);
if (hex === "0") {
hex += hex;
}
strhex += hex;
}
if (strhex.length! == 7) {
strhex = das;
}
return strhex;
} else if (reg.test (das)) {
var anum = that.replace (/#/, ""). split ("");
if (anum.length === 6) {
gib das zurück;
} else if (anum.length === 3) {
var numhex = "#";
für (var i = 0; i <anum.length; i+= 1) {
Numhex += (Anum +Anum);
}
Numhex zurückgeben;
}
}anders{
gib das zurück;
}};
/*Konvertieren Sie die hexadezimale Farbe in das RGB -Format*//////////
String.prototype.colorrgb = function () {
var scolor = this.tolowerCase ();
if (scolor && reg.test (scolor)) {
if (scolor.length === 4) {
var scolornew = "#";
für (var i = 1; i <4; i+= 1) {
scolornew+= scolor.lice (i, i+1) .concat (scolor.lice (i, i+1));
}
scolor = scolornew;
}
// sechsstellige Farbwerte verarbeiten
var scolorchange = [];
für (var i = 1; i <7; i+= 2) {
scolorchange.push (parseInt ("0x"+scolor.lice (i, i+2)));
}
return "rgb (" + scolorchange.join (",") + ")";
}anders{
Return Scolor;
}};
Verwenden Sie die Farbkonvertierungsmethode:
Die Codekopie lautet wie folgt:
AR SRGB = "RGB (23, 245, 56)", Shex = "#34538b";
var shexcolor = srgb.colorhex ();
var srgbcolor = shex.colorrgb ();