update-css-variables.ts 905 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * 更新 CSS 变量的函数
  3. * @param variables 要更新的 CSS 变量与其新值的映射
  4. */
  5. function updateCSSVariables(
  6. variables: { [key: string]: string },
  7. id = '__vben-styles__',
  8. ): void {
  9. // 获取或创建内联样式表元素
  10. const styleElement =
  11. document.querySelector(`#${id}`) || document.createElement('style');
  12. styleElement.id = id;
  13. // 构建要更新的 CSS 变量的样式文本
  14. let cssText = ':root {';
  15. for (const key in variables) {
  16. if (Object.prototype.hasOwnProperty.call(variables, key)) {
  17. cssText += `${key}: ${variables[key]};`;
  18. }
  19. }
  20. cssText += '}';
  21. // 将样式文本赋值给内联样式表
  22. styleElement.textContent = cssText;
  23. // 将内联样式表添加到文档头部
  24. if (!document.querySelector(`#${id}`)) {
  25. setTimeout(() => {
  26. document.head.append(styleElement);
  27. });
  28. }
  29. }
  30. export { updateCSSVariables };