我正在尝试创建一个黑暗模式切换按钮,一切正常。深色模式在我的网站上有效,但是当我刷新页面或转到其他文章时,我应该再次打开该按钮。这是我在网站https://codepen.io/pen/?template=poyYapw上使用的简化代码。另外,myFunction1
在我的网站上不起作用,我不知道为什么。 myFunction1
正在使用Codepen,w3schools等,但在我的网站上却无法使用。谁能为我提供一个可以解决这两个问题的javascript函数。
答案 0 :(得分:0)
我建议使用localStorage。
您可能不需要,但是有一种方法可以检测暗模式:How do I detect dark mode using JavaScript?
如果使用检测,请将布尔值保存到检测到暗模式的localStorage中。
检测在这里不起作用,但是应该在您的网站上。
var dark = localStorage.getItem("darkmode") || "false";
var detected = localStorage.getItem("dmodedetected") || "false";
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches & detected == "false") {
document.body.classList.add("darkmode");
}
detected = true;
localStorage.setItem("dmodedetected", "true");
function toggledmode() {
if (dark == "false") {
dark = "true";
document.body.classList.remove("darkmode");
}
else {
dark = "false";
document.body.classList.add("darkmode");
}
localStorage.setItem("darkmode", dark);
}
body {
background-color: white;
}
body.darkmode {
background-color: black;
}
<html>
<body>
<button onclick="toggledmode()">Toggle</button>
<script>
</script>
</body>
</html>