我目前有一个切换按钮,用于切换<body>上的类.dark-mode,然后将首选项保存到本地存储中。
不过,默认情况下,它是在轻量级主题中加载的。
我正在寻找使它,以便如果客户是prefers-color-scheme: dark,它会自动切换到黑暗模式,如果不是,那么它保持在光明。
<script>
/* Dark Mode Selection */
// On page load set the theme.
(function() {
let onpageLoad = localStorage.getItem("theme") || "";
let element = document.body;
element.classList.add(onpageLoad);
document.getElementById("theme").textContent =
localStorage.getItem("theme") || "light";
})();
function themeToggle() {
let element = document.body;
element.classList.toggle("dark-mode");
let theme = localStorage.getItem("theme");
if (theme && theme === "dark-mode") {
localStorage.setItem("theme", "");
} else {
localStorage.setItem("theme", "dark-mode");
}
document.getElementById("theme").textContent = localStorage.getItem("theme");
}
</script>我不确定如何让它在第一次加载时默认为他们喜欢的颜色。
发布于 2021-06-10 20:24:14
简单地阅读documentation,即使没有JS也会显示答案:
.day { background: #eee; color: black; }
.night { background: #333; color: white; }
@media (prefers-color-scheme: dark) {
.day.dark-scheme { background: #333; color: white; }
.night.dark-scheme { background: black; color: #ddd; }
}
@media (prefers-color-scheme: light) {
.day.light-scheme { background: white; color: #555; }
.night.light-scheme { background: #eee; color: black; }
}
.day, .night {
display: inline-block;
padding: 1em;
width: 7em;
height: 2em;
vertical-align: middle;
}https://stackoverflow.com/questions/67920955
复制相似问题