定义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

09-14 05:49