GitHub 夜间模式实现原理拆解

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/

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值