vue+js+css实现动态换肤,切换活动主题

文章介绍了如何通过CSS的:root伪类定义全局变量,创建不同主题的样式文件,然后在JavaScript中动态设置document.documentElement的theme属性来切换页面样式。同时,文章提供了SCSS变量的使用示例,以及在Vue组件中应用这些样式的例子。
摘要由CSDN通过智能技术生成

知识点:
样式切换主要运用:root
:root是一个伪类,表示文档根元素,所有主流浏览器均支持 ,除了 IE8 及更早的版本。
在:root中声明相当于全局属性,只要当前页面引用了:root segment所在文件,都可以使用var()来引用。
-- 这样写法加上样式名称 例如:--background-color 引用:var(--background-color)

步骤如下(简单举个列子哈~)
1、新建theme1.css文件
主题主要样式

/*定义样式 主题名称*/
:root[theme='theme1'] { 
  --title-text-color: #fff;
  --btn-bg: url("图片地址");
  --background-color:red;
}

2、theme2.css文件

/*定义样式 主题名称*/
:root[theme='theme2'] { 
  --title-text-color: #498be8;
  --btn-bg: url("图片地址");
  --background-color:yellow;
}

主题样式运用
3.theme.scss文件

$color: red;
$color3: var(--test,gray);//用var来放--test变量名,默认值为gray(test变量名可任取,默认值不能是字符串)
.red{
  color:var(--title-text-color);
  background:$color;
}
.bg{
  background: var(--btn-bg) no-repeat;
}
body,html{
  background-color: var(--background-color);
}
//把scss变量暴露出去
:export {
  newColor3: $color3;
}

4、theme.js

import "../style/theme1.css"
import "../style/theme2.css"
import '../style/theme.scss'
//默认theme1样式 对应root变量名
document.documentElement.setAttribute("theme","theme1");

//此方法可以更改scss变量
//document.getElementsByTagName('body')[0].style.setProperty('--test', 'yellow');

5、最后main.js中全局引入theme.js 就好啦~

import "./theme/theme"

具体页面点击更改样式

<template>
  <div>
    <button v-for="(item,index) of styles" @click="changeStyle(item)">{{item.name}}</button>
  </div>
</template>

<script>
  export default {
    data(){
      return {
        styles:[
          {
            name:"红",
            theme:"theme1"
          },
          {
            name:"黄",
            theme:"theme2"
          }
        ]
      }
    },
    methods:{
      changeStyle(item){
        document.documentElement.setAttribute("theme",item.theme);
      },
    }
  }
</script>

<style lang="scss" scoped>
//scss引用
  // @import "../style/theme.scss";
  // .red{
  //   color: #FFF;
  //   background: $color1;
  // }
  // .blue{
  //   background:$color2;
  // }
  // .yellow{
  //   background: $color3;
  // }
</style>

效果图
在这里插入图片描述
在这里插入图片描述

如有问题欢迎指正~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值