当用户选择启用暗模式的选项时,如何在localStorage中进行设置,以便他们刷新页面时仍保持暗模式?

时间:2019-02-25 00:15:50

标签: javascript html css local-storage

没关系,我自己修好了。只需修复index.html中的错误就可以了

1 个答案:

答案 0 :(得分:0)

编辑:

抱歉-请确保将您的scripts标签添加到body标签的末尾,以便当脚本运行时document.body存在:

<head></head>
<body>
  <!-- all your elements -->
  <button></button>
  <!-- Add scripts here -->
</body>

首先,在加载应用程序时,您应该有一个脚本,该脚本读取localStorage并将主题应用到您的身体(如果有)

<script>
  // check if THEME exists in localStorage - you may change the storage key 'THEME' to whatever you like in your code
  var themeClass = localStorage.getItem('THEME');
  if (themeClass) {
    document.body.className = themeClass;
  }
</script>

然后,您可能需要对toggleDarkLight函数进行一些更改

<script>
  // className can be either 'dark-mode' or 'light-mode'
  function toggleDarkLight(className) {
    // set className to your body
    document.body.className = className;

    // store in localStorage
    localStorage.setItem('THEME', className);
  }
</script>

最后,HTML中的按钮可以使用toggleDarkLight功能

<button onclick="toggleDarkLight('dark-mode')">I like it dark!</button>
<button onclick="toggleDarkLight('light-mode')">Let there be light!</button>