跳到主要内容

手写方案

RGB 色值 To 十六进制色值


function setRGBTo16(str) {
const reg = /^(rgb|RGB)/;
if (!reg.test(str)) {
return;
}
const arr = str.slice(4, str.length - 1).split(",");
let color = "#";
for (let i = 0; i < arr.length; i++) {
let t = Number(arr[i]).toString(16);
if (t.length < 2) {
t = t + "0";
}
color += t;
}
return color;
}

十六进制色值 To RGB 色值


function set16ToRGB(str) {
const reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
if (!reg.test(str)) {
return;
}
let newStr = str.toLowerCase().slice(1);
let len = newStr.length;
if (len === 3) {
let t = "";
for (let i = 0; i < len; i++) {
t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1));
}
newStr = t;
}
const arr = [];
for (let i = 0; i < 6; i = i + 2) {
let s = newStr.slice(i, i + 2);
arr.push(parseInt("0x" + s));
}
return `rgb(${arr.join(",")})`;
}