hex颜色转RGB
hex2Rgb(str) {str = str.replace("#", "");const hxs = str.match(/../g);for (let index = 0; index < 3; index++) hxs[index] = parseInt(hxs[index], 16);return hxs;
}
RGB转HXS
rgb2hex(r,g,b){const hexs = [r.toString(16), g.toString(16), b.toString(16)];for (let index = 0; index < 3; index++){cons isHave=hexs[index].length == 1;if (isHave) hexs[index] = "0" + hexs[index];}return "#" + hexs.join("");
}
颜色加深
getDark(color, level) {const rgb = hex2rgb(color);for (let index = 0; index < 3; index++){rgb[index] = Math.floor(rgb[index] * (1 - level))}return rgb2Hex(rgb[0], rgb[1], rgb[2]);
}
颜色变淡
getLight(color, level) {const rgb = this.hex2rgb(color);for (let index = 0; index < 3; index++){rgbc[index] = Math.floor((255 - rgbc[index]) * level + rgbc[index])}return rgb2hex(rgb[0], rgb[1], rgb[2]);
}
定义后端返回主题色
定义的参考色,在开发的过程中希望后端人员能遵循
const themeConf={primary: '#183ee4',success: '#0cce63',warn: '#ff4900',danger: '#f00c63'
}
getTheme(temeConf) {const obj={};Object.keys(temeConf).forEach(key => {let color = temeConf[key];// 用于按钮点击颜色const dColor = this.getDark(color, 0.2);obj[`--${key}`] = color;obj[`--${key}--active`] = dColor;for (let num = 1; num <= 4; num++) {const val = this.getLightColor(color, num / 10);obj[`--${key}-${num}`] = val;}});return obj;
}
将组元录入
1、在index.html内添加style标签录入(可录入::root下不挂在到任何标签)
let styleDom=document.getElementById('#sysCssElemnet');
if(!styleDom){styleDom=document.createElement("style");styleDom.id="#sysCssElemnet";document.head.append(styleDom);
}
const themeObj=getTheme(themConf).toString();
styleDom.innerHTML=`:root{${themeObj}}`;
2、将组元录入到html
let html=document.documentElement;
const themeObj=getTheme(themConf);
Object.keys(themeObj).forEach(key=>html.style.setProperty(key,colorObj[key]));
注:如果采用第二种方式录入,建议可直接在getTheme时直接在for循环中setProperty相关组元属性