简单方案
第一步
在head中声明<meta name="color-scheme" content="light dark">
,声明当前页面支持 light 和 dark 两种模式
第二步
设置不同模式下的全局样式变量,供全局子元素引用,实现模式修改,全局样式一起修改的效果。
注:1.有些属性如background不能实现继承,所以要实现不同元素背景色的统一修改,只能是不同元素使用同一变量。模式修改,变量值会修改,从而实现样式的切换
// 字体
$font-light-color-1: #1b1b1b;
$font-dark-color-1: #1b1b1b;
//背景
$bg-light-color-1: #fff;
$bg-dark-color-1: #1b1b1b;
@mixin light-theme {
color-scheme: light; // 浏览器提供的元素 UI 中使用的颜色与配色方案的意图相匹配。例如滚动条、拼写检查下划线、表单控件等。
--text-primary: #{$font-light-color-1};
}
@mixin dark-theme {
color-scheme:dark; // 浏览器提供的元素 UI 中使用的颜色与配色方案的意图相匹配。例如滚动条、拼写检查下划线、表单控件等。
--text-primary: #{$font-dark-color-1};
}
:root{
@media (prefers-color-scheme: light) {
@include light-theme;
}
@media (prefers-color-scheme: dark) {
@include dark-theme;
}
}
//颜色较多的情况,建议使用CSS变量对颜色值进行管理
第三步:
在项目中使用定义的变量,例如
.themeBtn {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
color: var(--text-primary);
border: 1px solid var(--border-primary);
cursor: pointer;
}
darkmode-switch-btn的实现方案:
第一步:为html添加meta标签
const html = document.documentElement;
if (window && html) {
// 插入 meta 标签
var oMeta = document.createElement("meta");
oMeta.content = "light dark";
oMeta.name = "color-scheme";
document.getElementsByTagName("head")[0].appendChild(oMeta);
}
第二步:初始化时,为html添加class
created(){
const theme = window.localStorage.getItem("theme");
this.mode=theme;
const html = document.documentElement;
if (window && html) {
html.className = theme;
html.style.backgroundColor = "";
}
},
第三步:切换主题时,改变html的class,使用不同模式的样式
handleCommand(theme) {
const html = document.documentElement;
if (window && html) {
html.className = theme;
html.style.backgroundColor = "";
window.localStorage.setItem("theme", theme);
this.mode = theme;
}
},
第四步:完成不同模式的css
// 字体
$font-light-color-1: #1b1b1b;
$font-dark-color-1: #1b1b1b;
//背景
$bg-light-color-1: #fff;
$bg-dark-color-1: #1b1b1b;
@mixin light-theme {
color-scheme: light;
// 浏览器提供的元素 UI 中使用的颜色与配色方案的意图相匹配。例如滚动条、拼写检查下划线、表单控件等。
--nav-bg:$bg-light-color-1
}
@mixin dark-theme {
color-scheme: dark;
// 浏览器提供的元素 UI 中使用的颜色与配色方案的意图相匹配。例如滚动条、拼写检查下划线、表单控件等。
--nav-bg:$bg-dark-color-1
}
.light{
@include light-theme
}
.dark{
@include dark-theme
}
:root:not(.light):not(.dark){
@media (prefers-color-scheme: light) {
@include light-theme;
}
@media (prefers-color-scheme: dark) {
@include dark-theme;
}
}
第五步:使用css变量
.themeBtn {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
color: var(--text-primary);
border: 1px solid var(--border-primary);
cursor: pointer;
}
完成!🎉🎉🎉
参考方案:
- 手动设置高亮或者暗夜模式,
- 修改访问地址 https://www.naiveui.com/zh-CN/light/components/button
- js切换css link地址element-uithemeswitching
- 切换class 隔离食用手册
- 既可跟随系统,也可以手动设置高亮或者暗夜模式
darkmode-switch-btn
github:https://github.com/startblingbling/darkmode-switch-btn