element-plus.ts 2.5 KB

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