SCSS 实现换肤

  scss 作为专业级CSS扩展语言,其功能是非常强大的。除了基本的嵌套外,还有 mixin(混合) 这些......
  这里简单的总结下,scss 实现白天和黑夜两种模式的换肤
  这是最近做的另一种使用scss换肤的方式 SCSS 实现换肤(二)

安装scss

  • npm install sass-loader node-sass --Save

实现

  • 新建一个主题颜色的 themes.scss,里边是对应主题的颜色变量

      $themes: (
        chalk: (
          homebackgrond: #fff,
          liveroommsgBg: #f7f8fd,
          headercolor: #39393f,
          useritembg: rgba(23, 35, 72, 0.4),
          .......
        )
        vintage: (
          homebackgrond: rgba(20, 21, 24, 1),
          liveroommsgBg: rgba(20, 21, 24, 1),
          headercolor: #fff,
          useritembg: rgba(52, 50, 59, 1),
          ......
        )
      )
    

    chalk:是白天模式
    vintage:是黑夜模式

  • 新建一个 handle.scss,获取相应的颜色变量及定义相关的方法

    1. 导入主题颜色文件
        @import './themes.scss';
      
    2. 遍历主题 map
        @mixin themeify {
          @each $theme-name, $theme-map in $themes {
            $theme-map: $theme-map !global;
            [data-theme="#{$theme-name}"] & {
              @content;
            }
          }
        }
      
    3. 声明一个根据 key,获取颜色的 function
        @function themed($key) {
          @return map-get($theme-map, $key);
        }
      
    4. 对应的样式混合
        @mixin background_color($color) {
          @include themeify {
            background: themed($color);
          }
        }
      
        @mixin font_color($color) {
          @include themeify {
            color: themed($color);
          }
        }
      

使用

  • 在文件中引入
      <style lang="scss" scoped>
        @import '../styles/handle.scss';
      <style>
    
  • 更改属性值
      window.document.documentElement.setAttribute('data-theme', this.theme);
    

效果

posted @ 2022-05-09 11:31  攻城Alone  阅读(762)  评论(0编辑  收藏  举报