javascript - 暗模式在加载期间不起作用

标签 javascript html jquery css

我正在尝试制作一个暗模式切换按钮,可以在单击时在暗模式和亮模式之间切换,用户首选项也使用 localStorage 存储。用户应手动按下按钮以切换到其他模式。如果用户选择的是深色模式,则每个页面都将处于深色模式,并且不会在刷新时转为浅色模式。到目前为止一切看起来都很好,但真正的问题在于加载时间。一个页面的加载时间将近 1 秒,在此期间,即使用户选择了深色模式,页面也似乎处于浅色模式。我不希望发生这种情况。如果用户的选择是黑暗的,我想在黑暗模式下加载时间部分。 这是我当前的代码:

<script>
const body = document.querySelector('body');
function toggleDark() {
  if (body.classList.contains('dark')) {
    body.classList.remove('dark');
    localStorage.setItem("theme", "light");
  } else {
    body.classList.add('dark');
    localStorage.setItem("theme", "dark");
  }
}

if (localStorage.getItem("theme") === "dark") {
  body.classList.add('dark');
}
</script>
<style>
body {background-color: #ffffff}
body.dark {background-color: #000000; color: #ffffff} 
</style>
<button class="dark-mode" id="btn-id" onclick="toggleDark()"></button>

最佳答案

另一种选择是在 <head> 中加载脚本元素,并在 html 上切换类元素

为此,您使用 document.documentElement.classList因为那是 HTML元素

然后将您的 CSS 更改为

html.dark body {}

等等 .. HTML 上的类选择器

html body {background-color: #ffffff}
html.dark body {background-color: #000000; color: #ffffff}
<script>
  const body = document.querySelector('body');

  function toggleDark() {
    if (document.documentElement.classList.contains('dark')) {
      document.documentElement.classList.remove('dark');
      //localStorage.setItem("theme", "light");
    } else {
      document.documentElement.classList.add('dark');
      //localStorage.setItem("theme", "dark");
    }
  }

  //if (localStorage.getItem("theme") === "dark") {
    document.documentElement.classList.add('dark');
  //}
</script>
<button class="dark-mode" id="btn-id" onclick="toggleDark()">DARK</button>

Due to restrictions, localStorage is unavailable on stack overflow - uncomment those lines to see it work

或者 - 参见 https://jsfiddle.net/e9zg2p4c/

关于javascript - 暗模式在加载期间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64167519/

相关文章:

javascript - 仅定位 jQuery 中的第一次点击

html - 如何选择我的 Bootstrap 导航栏链接以进行正确定位?

html - 在输入框末尾添加可点击区域

javascript - 如何录制从我的流媒体服务器播放的 Electron 视频

javascript - 如何在更改背景图像之间应用 JQuery 淡入淡出功能?

html - 垂直定位三个元素 : flexible box, 滚动框&固定框

javascript - 为什么 AJAX 不发送正确的 POST 数据?

jquery - 如何在移动设备上堆叠 Bootstrap 按钮

javascript - 如何使用javascript在DIV上创建卡片翻转效果

javascript - 添加合格的 XML 元素不会继承命名空间 URI