自己博客用的主题不支持黑暗模式,于是改了改别人的代码自己加了一个。用简单 JS+CSS 实现黑暗模式,灵感来源于 Dark Reader。支持
- 用户有偏好时使用用户偏好,无偏好时检测并使用系统/浏览器级别的黑暗模式设定(CSS Media Query 没有简单的用户 override 方式)
- 不影响图片、视频
- 可以方便的设定排除范围(如社交媒体相关图标)
(如有需要可以自己微调文本、链接等颜色)
原始代码来源: Adding dark mode to a Hugo static website without learning CSS | radu’s blog (radu-matei.com)
参考: 几行CSS让整站支持深色模式的探索与拓展 « 张鑫旭-鑫空间-鑫生活 (zhangxinxu.com)
效果
示例代码(为方便写在一起了,实际使用可以把 CSS / JS 拆开)
<!DOCTYPE html>
<html lang="cmn-Hans">
<head>
<meta charset="utf-8">
<title>Hello!</title>
<style id="dark-mode-theme" disabled>
html {
background-color: #ebebeb !important;
}
html {
filter: invert(1) hue-rotate(.5turn);
}
img:not(.icon-social),
video,
code {
filter: hue-rotate(180deg) contrast(100%) invert(100%);
}
</style>
</head>
<body>
<button id="dark-mode-toggle">to light</button>
<h1>Hello!</h1>
<p>Do you like dark mode?</p>
<img src="https://picsum.photos/200/300"></img>
<hr>
<img class="icon-social" src="https://github.com/favicon.ico"></img>
</body>
<script>
var toggle = document.getElementById("dark-mode-toggle");
var darkTheme = document.getElementById("dark-mode-theme");
// probe system default dark mode setting
var systemDefault = null
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
systemDefault = "dark";
} else {
systemDefault = "light";
}
// use user preference if possible
var savedTheme = localStorage.getItem("dark-mode-storage") || systemDefault;
setTheme(savedTheme);
toggle.addEventListener("click", () => {
if (toggle.innerText === "to dark" ) {
setTheme("dark");
} else if (toggle.innerText === "to light" ) {
setTheme("light");
}
});
function setTheme(mode) {
localStorage.setItem("dark-mode-storage", mode);
if (mode === "dark") {
darkTheme.disabled = false;
toggle.innerText = "to light";
} else if (mode === "light") {
darkTheme.disabled = true;
toggle.innerText = "to dark";
}
}
</script>
</html>