# 换肤

目前换肤方案:

  • 利用 class 命名空间

  • 准备多套CSS主题

  • 动态换肤

  • CSS变量换肤

# 利用 class 命名空间

利用 class 名称准备两个主题:

<style>
  .red-theme p{
    color: red
  }
  .blue-theme p{
    color: blue
  }
</style>

通过修改 body 的类名来修改元素的样式

# 准备多套CSS主题

  1. 准备多套样式文件

  2. 页面加载后,根据用户需求加载不同的样式文件

var link = document.createElement('link');
link.type = 'text/css';
link.id = "theme-blue";  
link.rel = 'stylesheet';
link.href = '/css/theme-blue.css';
document.getElementsByTagName("head")[0].appendChild(link);

# 动态换肤

生成一套主题,将主题配色配置写在 js 中,在浏览器中用 js 动态修改 style 标签覆盖原有的 CSS。

  1. 准备一套默认 theme.css 样式
/* theme.css */
.title {
  color: #FF0000
}
  1. 准备主题色配置
var colors = {
     red: {
       themeColor: '#FF0000'
     },
     blue: {
       themeColor: '#0000FF'
     }
   }
  1. 异步获取 theme.css ,将颜色值替换为关键词,关键字可以确保以后能多次换色
var styles = ''
axios.get('theme.css').then((resp=> {
 const colorMap = {
   '#FF0000': 'themeColor'
 }
 styles = resp.data
 Object.keys(colorMap).forEach(key => {
   const value = colorMap[key]
   styles = styles.replace(new RegExp(key, 'ig'), value)
 })
}))

style 变为:

.title {
  color: theme-color
}
  1. 把关键词再换回刚刚生成的相应的颜色值,并在页面上添加 style 标签
// console 中执行 writeNewStyle (styles, colors.blue)  即可变色
 function writeNewStyle (originalStyle, colors) {
    let oldEl = document.getElementById('temp-style')
    let cssText = originalStyle
     // 替换颜色值
    Object.keys(colors).forEach(key => {
      cssText = cssText.replace(new RegExp(key, 'ig'), colors[key])
    })
    const style = document.createElement('style')
    style.innerText = cssText
    style.id = 'temp-style'

    oldEl ? document.head.replaceChild(style, oldEl) : 
    document.head.appendChild(style)  // 将style写入页面
  }

此时style 变为:

.title {
  color: '#0000FF'
}

# CSS 变量换肤

利用 CSS 变量设置颜色, 用 js 动态修改 CSS 变量,进而换色

<html>
  <head>
    <title>CSS varies</title>
    <style>
      :root {
        --theme-color: red /* css 变量赋值位置 */
      }
      .title {
        color: var(--theme-color) /* 用css变量标记颜色 */
      }
    </style>
  </head>
  <body>
    <h3 class="title">CSS 变量换肤</h3>
    <script>
      // console 中执行 changceColor('blue') 即可变色
      function changeColor(color = 'blue') {
        document.documentElement.style.setProperty("--theme-color",color);
      }
    </script>
  </body>
</html>
  • 优点:只需一套 CSS 文件; 换肤不需要延迟等候;对浏览器性能要求低;可自动适配多种主题色;

  • 缺点: 不支持IE, 2016年前的 chrome,safari

# css in js