开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第25天,点击查看活动详情
前言
换主题功能也是常见的一种需求,怎么实现个人想法都不一样,本节介绍一下个人实现思路,供大家参考。
实现
CSS
主题相关的就是CSS,所以最简单的就是利用CSS,首先定义好几种主题样式,选择样式时候将根节点设置为对应样式。思路非常明确,重点是如何替换设置,我们可以分为三个步骤:
- 给根节点设置一个自定义属性比如'theme',属性值为样式名称。
- 利用属性选择器设置每个主题下面的样式。
属性选择器用来匹配带有特点属性的元素,用"[]"来匹配:
div[class='a'] {
/* 配置class为'a'的div */
color: red;
}
<div class="a">成功匹配</div>
<div>没有匹配</div>
- 选择时候用setAttribute方法去更新'theme'的属性值。
//样式
<style>
:root[theme='red'] {
color: red;
}
:root[theme='green'] {
color: green;
}
:root[theme='blue'] {
color: blue;
}
.button {
width: 20px;
height: 20px;
border-radius: 20px;
position: absolute;
top: 50px;
}
.btn1 {
right: 20px;
background-color: red;
}
.btn2 {
right: 50px;
background-color: green;
}
.btn3 {
right: 80px;
background-color: blue;
}
</style>
//body
<body>
<div class="button btn1" onclick="changeTheme('red')"></div>
<div class="button btn2" onclick="changeTheme('green')"></div>
<div class="button btn3" onclick="changeTheme('blue')"></div>
<h2>内容</h2>
<script>
function changeTheme(type) {
//window.document.documentElement 获取根元素
window.document.documentElement.setAttribute('theme', type);
}
</script>
</body>
利用CSS中属性选择器还是非常简便的,但现在项目中一般用的是scss、less来书写样式,下面我们来看下scss如何实现。
scss
scss是sass3.0版本之后的写法,换主题功能的思路是一样的,区别在于style部分,要将css转为scss写法,在此之前我们要了解scss相关的写法:
- $:定义变量,我们可以用变量来代替对应的属性值。
<style lang="scss" scoped>
$default: red;
// a标签字体会变成红色
a {
color: $default;
}
</style>
- @each:用于循环数组或map对象变量。它的用法跟for...in...类似:
$colorList: red, blue, green;
@each $item in $colorList {
.icon-#{$item} {
color: $item;
}
}
循环一个list,$item就是每一个元素值,#{}用来转换为插值,变量表示属性时必须要用插值。以上scss转换为css样式:
.icon-red {
color: red;
}
.icon-blue {
color: blue;
}
.icon-green {
color: green;
}
了解以上scss语法,我们换主题的css就可以改写为:
@each $item in $colorList {
:root[theme='#{$item}'] {
color: $item;
}
}
两者对比之下,scss的代码显得非常简洁。
总结
以上就是换主题功能的一个思路,开发中我们肯定需要打磨好每个主题的样式并且使用scss的语法去表述,我们需要熟悉scss语法。