知识点:
样式切换主要运用: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>
效果图
如有问题欢迎指正~~