使用JavaScript的HTML本地存储暗模式

问题描述

我试图对我的网站设置完全暗模式。差不多完成了,但是我有一个问题。当我重新加载页面时,暗模式会恢复为默认的亮模式。我该如何解决这个问题?我尝试了一些代码,但是没有用。我想使用本地存储,但是我不知道如何将其添加到我的代码中。有人可以帮我弄这个吗? 这是我的示例代码:

function darkmode() {
    var element = document.body;
    element.classList.toggle("dark-mode");
}
<html>
<head>
<style>
.card {
  background-color: red;
  color: green;
}
.dark-mode .card {
  background-color: black;
  color: white;
}


</style>
</head>
<body>
<button onclick="darkmode()">DARK MODE</button>
<div class="card">
  <h2>Title</h2>
  <div class="fkimg" style="height: 100px; width: 20%;">IMAGE</div>
  <a>Some text</a>
</div>

</body>
</html>

解决方法

对于您的示例代码,似乎最好的方法是在darkmode函数中添加一些内容:

function darkmode() {
  // all values retrieved from localStorage will be strings
  const wasDarkmode = localStorage.getItem('darkmode') === 'true';
  localStorage.setItem('darkmode',!wasDarkmode);
  const element = document.body;
  element.classList.toggle('dark-mode',!wasDarkmode);
}

function onload() {
  document.body.classList.toggle('dark-mode',localStorage.getItem('darkmode') === 'true');
}
<html>
<head>...</head>
<body onload="onload()">
  ...
</body>
</html>

MDN localStorage参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...