En el desarrollo diario, a menudo se usa la conversión mutua entre los valores del dominio de color en diferentes formatos. Aquí hay una solución.
La copia del código es la siguiente:
// Expresión regular del valor de color hexadecimal
var reg = /^#([0-9a-fa-f] {3} | [0-9a-fa-f] {6}) $ /;
/*RGB Conversión de color a hexadecimal*/
String.prototype.colorhex = function () {
var que = esto;
if (/^(rgb | rgb)/. test (that)) {
var acolor = that.replace (/(?:/(|/) | rgb | rgb)*/g, ""). Split (",");
var strhex = "#";
para (var i = 0; i <acolor.length; i ++) {
var hex = número (acolor) .tostring (16);
if (hex === "0") {
hex += hex;
}
strhex += hex;
}
if (strhex.length! == 7) {
strhex = that;
}
devolver strhex;
} else if (reg.test (that)) {
var anum = that.replace (/#/, ""). Split ("");
if (anum.length === 6) {
devolver eso;
} else if (anum.length === 3) {
var numhex = "#";
para (var i = 0; i <anum.length; i+= 1) {
numhex += (anum +anum);
}
devolver numhex;
}
}demás{
devolver eso;
}};
/*Convertir el color hexadecimal en formato RGB*/
String.prototype.colorrgb = function () {
var scolor = this.tOlowerCase ();
if (scolor && reg.test (scolor)) {
if (scolor.length === 4) {
var scolornew = "#";
para (var i = 1; i <4; i+= 1) {
scolornew+= scolor.slice (i, i+1) .concat (scolor.slice (i, i+1));
}
scolor = scolornew;
}
// procesar valores de color de seis dígitos
var scolorchange = [];
para (var i = 1; i <7; i+= 2) {
scolorchange.push (parseInt ("0x"+scolor.slice (i, i+2)));
}
return "rgb (" + scolorchange.Join (",") + ")";
}demás{
regresar scolor;
}};
Utilice el método de conversión de color:
La copia del código es la siguiente:
ar srgb = "rgb (23, 245, 56)", shex = "#34538b";
var shexcolor = srgb.colorhex ();
var srgbcolor = shex.colorrgb ();