css darkmode切换在relod上不断变回?

isr3a4wc  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(113)

我试图实现的图标的变化和停留,如果darkmode被激活,即.如果黑暗模式为真,图标将为太阳黑暗模式为假,图标为月亮。
但是,在重新加载页面之后,页面本身仍然处于黑暗模式,因为它存储在本地存储中,但图标会变回。
换句话说,我想要达到的是
darkmode = enabled then icon sun darkmode = null the icon moon

<button
          id="dark-mode-toggle"
          class="dark-mode-toggle"
          area-label="toggle dark mode"
        >
          <i class="bx bx-moon moon" id="moon"></i>
          <i class="bx bx-sun sun" id="sun"></i>
        </button>
/* Darkmode */
.dark-mode-toggle {
  background: transparent;
  border: none;
  cursor: pointer;
}

#moon {
  color: var(--a-clr);
  font-size: 2rem;
  display: block;
}

#sun {
  font-size: 2rem;

  color: var(--a-clr);
  display: block;
}
let darkMode = localStorage.getItem("darkMode");
const sun = document.getElementById("sun");
const moon = document.getElementById("moon");
const darkModeToggle = document.querySelector("#dark-mode-toggle");

const enableDarkMode = () => {
  document.documentElement.classList.add("darkmode");
  localStorage.setItem("darkMode", "enabled");
};

const disableDarkMode = () => {
  document.documentElement.classList.remove("darkmode");
  localStorage.setItem("darkMode", null);
};

darkModeToggle.addEventListener("click", () => {
  darkMode = localStorage.getItem("darkMode");

  if (darkMode !== "enabled") {
    enableDarkMode();
  } else {
    disableDarkMode();
  }
});

谢谢你!

insrf1ej

insrf1ej1#

您需要从darkMode初始更新图标的状态
尝试将其添加到JavaScript中。

if (darkMode === "enabled") {
  enableDarkMode();
} else {
  disableDarkMode();
}

相关问题