
夜晚浏览网页太亮,试试夜晚模式吧,此以 vue3 为例
本项目自定义了两种模式,即白天模式和夜晚模式,当然可以添加更多的模式。

- 新建一个 base.scss 文件,里面写上需要的主题颜色。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $themes: ( // 白天模式 light: ( bgColor: #ebeaea, textColor: #121212, cardBgColor: #ffffff, ), // 夜间模式 dark: ( bgColor: #121212, textColor: #ebeaea, cardBgColor: #3a3a3a, ) );
|
- 新建一个 theme.scss 文件,文件主要是解析 theme(这里主要是采自网上写法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| @mixin themeify { @each $theme-name, $theme-map in $themes { $theme-map: $theme-map !global; [data-theme="#{$theme-name}"] & { @content; } } }
@function themed($key) { @return map-get($theme-map, $key); }
@mixin background_color($color) { @include themeify { background-color: themed($color) !important; } }
@mixin font_color($color) { @include themeify { color: themed($color) !important; } }
@mixin border_color($color) { @include themeify { border-color: themed($color) !important; } }
|
- 新建 color.scss 文件,主要是自定义颜色样式,在项目任何地方即可使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @import "./theme.scss";
.page-bgColor { @include background_color("bgColor"); }
.basis-text-color { @include font_color("textColor"); }
.nav-card-bgColor { @include background_color("cardBgColor"); }
|
- 根据需求,切换主题。
- 假如这里有一个切换的按钮(这里使用两个 icon 代替)
1 2 3 4 5 6 7 8 9 10 11 12
| <div class="theme-icon"> <i class="iconfont icon-yueduqi_yewanmoshi-98 title" @click="handleChangeThemes" v-if="themeData.isDark" /> <i class="iconfont icon-baitianmoshi light title" @click="handleChangeThemes" v-else /> </div>
|
- 点击切换按钮切换主题(这里是用 vue3,并将其 ts 代码分离)
新建一个 changeTheme.ts 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { onMounted, reactive } from 'vue'
export const changeTheme = () => { const themeData = reactive({ isDark: false }) const handleChangeThemes = () => { themeData.isDark = !themeData.isDark if (themeData.isDark) { window.document.documentElement.setAttribute('data-theme', 'light') } else { window.document.documentElement.setAttribute('data-theme', 'dark') } } onMounted(() => { handleChangeThemes() }) return { themeData, handleChangeThemes } }
|
1 2 3 4 5 6 7 8 9 10
| export default defineComponent({ name: "", setup() { const { themeData, handleChangeThemes } = changeTheme() return { themeData, handleChangeThemes } } })
|