GitHub 目前已经支持夜间模式,周末分析了它的实现思路,先来看下它的两种模式效果:
它的实现思路其实核心有 4 点:
1、在 html 元素中不同模式中添加不同的属性选择器 data-color-mode='dark' 和 data-color-mode='light',比如夜间模式:
2、在不同属性选择器下把所有颜色值定义成变量,变量名相同,但值不同:
[data-color-mode=dark] {
--color-suyan-black: #010409;
--color-suyan-bg: #0d1117;
--color-text-primary: #c9d1d9;
}
[data-color-mode=light] {
--color-suyan-black: #010409;
--color-suyan-bg: #fff;
--color-text-primary: #24292e;
}
3、使用 var 来使用颜色值
body {
background-color: var(--color-suyan-bg);
}
.book-name, .author, .des {
color: var(--color-text-primary);
}
但是这个有个坑,发现在 IE 下 CSS 并不支持 var,估计 GitHub 已经放弃了 IE 用户,我也没有 IE 浏览器,有 IE 的朋友可以帮忙看看 IE 下是否有夜间模式。
4、当用户点击切换按钮时,直接修改 html 属性的值即可:
const ele = document.getElementsByTagName('html')[0];
const orgMode = ele.getAttribute('data-color-mode');
const targetMode = orgMode === 'dark' ? 'light' : 'dark';
ele.setAttribute('data-color-mode', targetMode);
我实现了一个 demo,可以体验下:
<!DOCTYPE html>
<html lang="en" data-color-mode="light"">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GitHub中的夜间模式实现预览探索</title>
<style>
[data-color-mode=dark] {
--color-suyan-black: #010409;
--color-suyan-bg: #0d1117;
--color-text-primary: #c9d1d9;
}
[data-color-mode=light] {
--color-suyan-black: #010409;
--color-suyan-bg: #fff;
--color-text-primary: #24292e;
}
body {
background-color: var(--color-suyan-bg);
}
.book-name, .author, .des {
color: var(--color-text-primary);
}
</style>
</head>
<body>
<h1 class="book-name">《读懂Vue编程思想》</h1>
<p class="author">作者:素燕</p>
<div class="des">帮助10W人入门并进阶前端</div>
<button onclick="changeMode()">切换</button>
<script>
window.changeMode = function (){
const ele = document.getElementsByTagName('html')[0];
const orgMode = ele.getAttribute('data-color-mode');
const targetMode = orgMode === 'dark' ? 'light' : 'dark';
ele.setAttribute('data-color-mode', targetMode);
console.log('change mode to ', targetMode);
};
</script>
</body>
</html>
关于属性选择器,其实在 vue-loader 中的 scoped 实现思路也利用了,可以看 scoped 减少了我对 CSS 样式冲突的焦虑。还有一点需要大家对 CSS 的权重要重点掌握,这两篇文章 聚齐了这3张宝图,搞懂CSS权重、第18天:CSS中的权重。大家加油。
长按关注
素燕《前端小课》
帮助 10W 人入门并进阶前端
官网:https://lefex.gitee.io/