No desenvolvimento diário, é frequentemente usada a conversão mútua entre os valores do domínio de cores em diferentes formatos. Aqui está uma solução.
A cópia do código é a seguinte:
// Expressão regular de valor de cor hexadecimal
var reg = /^#([0-9a-fa-f] {3} | [0-9a-fa-f] {6}) $ /;
/*Conversão de cores RGB em hexadecimal*/
String.prototype.colorhex = function () {
var que = this;
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 = número (acolor) .ToString (16);
if (hex === "0") {
Hex += Hex;
}
STRHEX += Hex;
}
if (strhex.length! == 7) {
STRHEX = isso;
}
retornar o strex;
} else if (reg.test (that)) {
var anum = that.replace (/#/, ""). split ("");
if (anum.length === 6) {
devolver isso;
} else if (anum.length === 3) {
var numhex = "#";
for (var i = 0; i <anum.length; i+= 1) {
numhex += (anum +anum);
}
retornar numhex;
}
}outro{
devolver isso;
}};
/*Converta a cor hexadecimal em formato RGB*/
String.prototype.colorrgb = function () {
var scolor = this.TolowerCase ();
if (scolor && reg.test (scolor)) {
if (scolor.length === 4) {
var scolornew = "#";
for (var i = 1; i <4; i+= 1) {
scolornew+= scolor.slice (i, i+1) .concat (scolor.slice (i, i+1));
}
scolor = scolornew;
}
// Processar valores de cores de seis dígitos
var scolorChange = [];
for (var i = 1; i <7; i+= 2) {
scolorchange.push (parseint ("0x"+scolor.slice (i, i+2)));
}
retornar "rgb (" + scolorchange.join (",") + ")";
}outro{
retornar Scolor;
}};
Use o método de conversão de cores:
A cópia do código é a seguinte:
ar srgb = "rgb (23, 245, 56)", shex = "#34538b";
var shexcolor = srgb.colorhex ();
var srgbcolor = shex.colorrgb ();