换肤功能实现逻辑

86 阅读2分钟

思路: 想要实现换肤功能首先想到的应该会使类似语言国际化的场景,既对应类型的映射字典,即a=>b,暗黑模式=>暗黑模式的样式,dark=>darkStyle

const dark = {
    theme:'#000';
    '--text-color-45': rgba(0, 13, 31, 0.45);
    '--text-color-85': rgba(0, 13, 31, 0.85);
    '--text-color-100': rgba(255, 255, 255, 1);
}
const light = {
    theme:'#fff';
    '--text-color-85': rgba(255, 255, 255, 0.85);
    '--text-color-45': rgba(255, 255, 255, 0.45);
    '--text-color-100': rgba(0, 13, 31, 1);
}

document.documentElement.setAttribute(
    'data-theme',
    app.theme ? 'dark' : 'light'
  )

想要实现上面功能其实很简单无非就是根元素的整体样式变化,而后子元素对根元素的样式应用,在切换主题的同时映射值随之发生改变

对应代码实现

1.在assets文件下新建一个css的主题样式

2.设置对应的变量类型

html[data-theme='light'] {
  --theme-color: #2da74e;
  --main-bg: #f7f7f8;
  --carditem-bg: rgba(255, 255, 255, 1), --primary: var(--theme-color);
  --primary-border-color: var(--theme-color);
  --text-color-45: rgba(0, 13, 31, 0.45);
  --text-color-85: rgba(0, 13, 31, 0.85);
  --text-color-100: rgba(255, 255, 255, 1);
  // el
  --el-text-color-primary: var(--theme-color);
  --el-border-color: var(--theme-color);
  --el-text-color-placeholder: var(--theme-color);
  --el-border-color-hover: var(--theme-color);
  --el-color-primary: var(--theme-color);
  // svg
  .pie-empty-css{
  --pd-1:#D9DBDE;
  --pd-2:#E5E6E8;
  --pd-3: #F2F3F4;
  }
  
  
}

html[data-theme='dark'] {
  --theme-color: #0e0032;
  --main-bg: #0e0032;
  --carditem-bg: rgba(38, 25, 98, 0.2);
  --text-color-85: rgba(255, 255, 255, 0.85);
  --text-color-45: rgba(255, 255, 255, 0.45);
  --text-color-100: rgba(0, 13, 31, 1);
  // el
  --el-text-color-primary: var(--theme-color);
  --el-border-color: var(--theme-color);
  --el-text-color-placeholder: var(--theme-color);
  --el-border-color-hover: var(--theme-color);
  --el-color-primary: var(--theme-color);
  // svg
  .pie-empty-css{
    --pd-1:#0F5041;
    --pd-2:#0D4336;
    --pd-3: #0B372D;
  }
  

}

3.在换肤功能上添加对应的触发事件

    const theme = 'dark'

    const changeSkin =(theme) =>{
        document.documentElement.setAttribute(
        'data-theme',
        theme
        )
    }
    

总结:换肤场景其实并不复杂,结合一些类似的场景,在考虑css是否支持变量替换,综合输出即可实现换肤功能