一,首先搭建基础的页面结构
<template>
<div>
<button>切换主题1</button>
<button>切换主题2</button>
<h1>这是一段测试文字</h1>
</div>
</template>
<script>
export default {
data () {
return {
// 默认背景颜色
themeBgColor: '#fff',
// 默认文字颜色
themeColor: '#000'
}
}
}
</script>
<style>
</style>
这里是一段普通的基础代码,里面有两个用于切换主题的按钮,和一段测试文字
二,使用css3中的var创建样式变量
这里使用了–bgColor和–textColor样式变量,并且将vue中声明的变量赋值,使默认样式生效
注意点1:样式变量名必须要--开头
注意点2:在style标签中使用样式变量需要用var函数
<template>
<div
class="container"
:style="{
'--bgColor': themeBgColor,
'--textColor': themeColor,
}"
>
<button>切换主题1</button>
<button>切换主题2</button>
<h1 class="text">这是一段测试文字</h1>
</div>
</template>
<script>
export default {
data () {
return {
// 默认背景颜色
themeBgColor: '#fff',
// 默认文字颜色
themeColor: '#000'
}
}
}
</script>
<style>
.container {
background: var(--bgColor);
}
.text {
color: var(--textColor);
}
</style>
基本的样式架构已经搭建好了,接下来就是动态改变vue中的变量,来达到动态切换主题的效果…
三,动态切换主题
这里给两个主题切换按钮绑定事件,传入不同的参数,使样式变量和vue中的变量关联,达到切换主题的效果
<template>
<div
class="container"
:style="{
'--bgColor': themeBgColor,
'--textColor': themeColor,
}"
>
<!-- 绑定切换主题事件 -->
<button @click="changeTheme('#000', '#fff')">切换主题1</button>
<button @click="changeTheme('red', 'yellow')">切换主题2</button>
<h1 class="text">这是一段测试文字</h1>
</div>
</template>
<script>
export default {
data () {
return {
// 默认背景颜色
themeBgColor: '#fff',
// 默认文字颜色
themeColor: '#000'
}
},
methods: {
changeTheme (bgColor, textColor) {
this.themeBgColor = bgColor
this.themeColor = textColor
}
}
}
</script>
<style>
.container {
background: var(--bgColor);
}
.text {
color: var(--textColor);
}
</style>
四,如果你没有使用vue,而是想用原生js来实现动态主题切换,那么你可以采用下面的写法
我们可以使用js提供的setProperty来主动修改dom节点上的style属性,也能达到动态修改主题的效果
<template>
<div
class="container"
:style="{
'--bgColor': '#fff',
'--textColor': '#000',
}"
>
<!-- 绑定切换主题事件 -->
<button @click="changeTheme">切换主题</button>
<h1 class="text">这是一段测试文字</h1>
</div>
</template>
<script>
export default {
data () {
return {
}
},
methods: {
changeTheme () {
document.querySelector('.container').style.setProperty('--bgColor', 'yellow')
document.querySelector('.container').style.setProperty('--textColor', 'red')
}
}
}
</script>
<style>
.container {
background: var(--bgColor);
}
.text {
color: var(--textColor);
}
</style>