admin-vben/packages/@core/shared/toolkit/src/update-css-variables.ts

36 lines
905 B
TypeScript
Raw Normal View History

2024-06-23 11:17:31 +00:00
/**
* CSS
* @param variables CSS
*/
function updateCSSVariables(
variables: { [key: string]: string },
id = '__vben-styles__',
): void {
// 获取或创建内联样式表元素
const styleElement =
document.querySelector(`#${id}`) || document.createElement('style');
styleElement.id = id;
// 构建要更新的 CSS 变量的样式文本
let cssText = ':root {';
for (const key in variables) {
if (Object.prototype.hasOwnProperty.call(variables, key)) {
cssText += `${key}: ${variables[key]};`;
}
}
cssText += '}';
// 将样式文本赋值给内联样式表
styleElement.textContent = cssText;
// 将内联样式表添加到文档头部
if (!document.querySelector(`#${id}`)) {
setTimeout(() => {
document.head.append(styleElement);
});
}
}
export { updateCSSVariables };