You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.1 KiB

  1. /* 动态改变element-plus主题色 */
  2. import rgbHex from "rgb-hex";
  3. import color from "css-color-function";
  4. import epCss from "element-plus/dist/index.css";
  5. // 色值表
  6. const formula = {
  7. "shade-1": "color(primary shade(10%))",
  8. "light-1": "color(primary tint(10%))",
  9. "light-2": "color(primary tint(20%))",
  10. "light-3": "color(primary tint(30%))",
  11. "light-4": "color(primary tint(40%))",
  12. "light-5": "color(primary tint(50%))",
  13. "light-6": "color(primary tint(60%))",
  14. "light-7": "color(primary tint(70%))",
  15. "light-8": "color(primary tint(80%))",
  16. "light-9": "color(primary tint(90%))"
  17. };
  18. // 把生成的样式表写入到style中
  19. export const writeNewStyle = (newStyle: string): void => {
  20. const style = window.document.createElement("style");
  21. style.innerText = newStyle;
  22. window.document.head.appendChild(style);
  23. };
  24. // 根据主题色,生成最新的样式表
  25. export const createNewStyle = (primaryStyle: string): string => {
  26. // 根据主色生成色值表
  27. const colors = createColors(primaryStyle);
  28. // 在当前ep的默认样式表中标记需要替换的色值
  29. let cssText = getStyleTemplate(epCss);
  30. // 遍历生成的色值表,在 默认样式表 进行全局替换
  31. Object.keys(colors).forEach(key => {
  32. cssText = cssText.replace(
  33. new RegExp("(:|\\s+)" + key, "g"),
  34. "$1" + colors[key]
  35. );
  36. });
  37. return cssText;
  38. };
  39. export const createColors = (primary: string) => {
  40. if (!primary) return;
  41. const colors = {
  42. primary
  43. };
  44. Object.keys(formula).forEach(key => {
  45. const value = formula[key].replace(/primary/, primary);
  46. colors[key] = "#" + rgbHex(color.convert(value));
  47. });
  48. return colors;
  49. };
  50. const getStyleTemplate = (data: string): string => {
  51. const colorMap = {
  52. "#3a8ee6": "shade-1",
  53. "#409eff": "primary",
  54. "#53a8ff": "light-1",
  55. "#66b1ff": "light-2",
  56. "#79bbff": "light-3",
  57. "#8cc5ff": "light-4",
  58. "#a0cfff": "light-5",
  59. "#b3d8ff": "light-6",
  60. "#c6e2ff": "light-7",
  61. "#d9ecff": "light-8",
  62. "#ecf5ff": "light-9"
  63. };
  64. Object.keys(colorMap).forEach(key => {
  65. const value = colorMap[key];
  66. data = data.replace(new RegExp(key, "ig"), value);
  67. });
  68. return data;
  69. };