Dans le développement quotidien, la conversion mutuelle entre les valeurs du domaine de couleur dans différents formats est souvent utilisée. Voici une solution.
La copie de code est la suivante:
// Expression régulière de la valeur de couleur hexadécimale
var reg = / ^ # ([0-9a-fa-f] {3} | [0-9a-fa-f] {6}) $ /;
/ * Conversion de couleur RVB en hexadécimal * / /
String.prototype.colorhex = fonction () {
var that = this;
if (/ ^ (rgb | rgb) /. test (that)) {
var acolor = that.replace (/ (?: / (| /) | rgb | rgb) * / g, ""). Split (",");
var strhex = "#";
pour (var i = 0; i <acolor.length; i ++) {
var hex = nombre (acolor) .tostring (16);
if (hex === "0") {
hex + = hex;
}
strhex + = hex;
}
if (strhex.length! == 7) {
strhex = that;
}
retour strhex;
} else if (reg.test (that)) {
var anum = that.replace (/ # /, ""). Split ("");
if (anum.length === 6) {
retourner cela;
} else if (anum.length === 3) {
var numhex = "#";
pour (var i = 0; i <anum.length; i + = 1) {
numhex + = (anum + anum);
}
retour numhex;
}
}autre{
retourner cela;
}};
/ * Convertir la couleur hexadécimale au format RVB * /
String.prototype.colorrgb = fonction () {
var scolor = this.tolowercase ();
if (scolor && reg.test (scolor)) {
if (scolor.length === 4) {
var scolorn = "#";
pour (var i = 1; i <4; i + = 1) {
Scolornew + = Scolor.slice (i, i + 1) .concat (scolor.slice (i, i + 1));
}
SCOLOR = SCOLORNEW;
}
// traite les valeurs de couleur à six chiffres
var scolorchange = [];
pour (var i = 1; i <7; i + = 2) {
scolorchange.push (parseInt ("0x" + scolor.slice (i, i + 2)));
}
return "rgb (" + scolorchange.join (",") + ")";
}autre{
retour Scolor;
}};
Utilisez la méthode de conversion des couleurs:
La copie de code est la suivante:
ar srgb = "rgb (23, 245, 56)", shex = "# 34538b";
var shexcolor = srgb.colorhex ();
var srgBColor = Shex.ColorrGB ();