ในการพัฒนาประจำวันมักจะใช้การแปลงร่วมกันระหว่างค่าโดเมนสีในรูปแบบที่แตกต่างกันมักจะใช้ นี่คือวิธีแก้ปัญหา
การคัดลอกรหัสมีดังนี้:
// การแสดงออกปกติของค่าสีเลขฐานสิบหก
var reg = /^#([0-9a-fa-f] {3} | [0-9a-fa-f] {6}) $ /;
/*การแปลงสี rgb เป็น hexadecimal*/
string.prototype.colorhex = function () {
var that = this;
if (/^(rgb | rgb)/. ทดสอบ (ที่)) {
var acolor = That.replace (/(?:/(|/) | rgb | rgb)*/g, ""). แยก (",");
var strhex = "#";
สำหรับ (var i = 0; i <acolor.length; i ++) {
var hex = number (acolor) .tostring (16);
if (hex === "0") {
hex += hex;
-
strhex += hex;
-
if (strhex.length! == 7) {
strhex = นั่น;
-
กลับ Strhex;
} อื่นถ้า (reg.test (นั้น)) {
var anum = that.replace (/#/, ""). แยก ("");
if (anum.length === 6) {
กลับมา;
} อื่นถ้า (anum.length === 3) {
var numhex = "#";
สำหรับ (var i = 0; i <anum.length; i+= 1) {
numhex += (anum +anum);
-
กลับ numhex;
-
}อื่น{
กลับมา;
-
/*แปลงสีเลขฐานสิบหกเป็นรูปแบบ RGB*/
string.prototype.colorrgb = function () {
var scolor = this.toLowerCase ();
if (scolor && reg.test (scolor)) {
if (scolor.length === 4) {
var scolornew = "#";
สำหรับ (var i = 1; i <4; i+= 1) {
scolornew+= scolor.slice (i, i+1) .concat (scolor.slice (i, i+1));
-
Scolor = Scolornew;
-
// ประมวลผลค่าสีหกหลัก
var scolorchange = [];
สำหรับ (var i = 1; i <7; i+= 2) {
scolorchange.push (parseint ("0x"+scolor.slice (i, i+2)));
-
กลับ "rgb (" + scolorchange.join (",") + ")";
}อื่น{
กลับมาสกอล;
-
ใช้วิธีการแปลงสี:
การคัดลอกรหัสมีดังนี้:
AR SRGB = "RGB (23, 245, 56)", Shex = "#34538B";
var shexcolor = srgb.colorhex ();
var srgbColor = shex.colorrgb ();