elementui 更换主题色

定义CSS变量,由var()函数来获取值。

复制代码
/* 设定值 */
:root {
    --background-color: #FF0000;
}
/* 获取值 */
div {
    background-color: var(--background-color);
}

JS获取变量

复制代码
const element = document.documentElement;
const style = window.getComputedStyle(element);
const value = style.getPropertyValue('`background-color`');

JS设置变量

复制代码
el.style.setProperty('background-color', value)

动态修改 ElementUI 主题色

复制代码
changeTheme(color, theme) {
      const version = require('element-ui/package.json').version
      const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
      const id = 'chalk-style'
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4 && xhr.status === 200) {
            const res = xhr.responseText
            const newStyle = res.replace(new RegExp(color, 'ig'), theme)
            let styleTag = document.getElementById(id)
            if (!styleTag) {
              styleTag = document.createElement('style')
              styleTag.setAttribute('id', id)
              document.head.appendChild(styleTag)
            }
            styleTag.innerText = newStyle
            resolve()
          }
        }
        xhr.open('GET', url)
        xhr.send()
      })
}

1

相关推荐
2分钟速写快排4 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge6665 小时前
JavaScript:BOM 详解
前端
Penge6666 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge6666 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge6666 小时前
Sass 了解
前端
Penge6667 小时前
Webpack 打包从 0 到 1 实战笔记
前端
Penge6667 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge6667 小时前
Ant Design(Antd)了解
前端
wangruofeng8 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github
Penge6668 小时前
JavaScript 核心语法速通
前端