【问题标题】:how do i make light mode stay when switching pages?切换页面时如何保持灯光模式?
【发布时间】:2022-12-17 17:36:25
【问题描述】:

所以我的网站默认是深色模式,我添加了一个浅色模式按钮让网站变亮 我想在切换页面时保持灯光模式,如何在切换页面时保持灯光模式。 JS


//light mode for home page
function lightMode() {


    var element = document.body;
    element.classList.toggle("light-mode");

    var buttonText = document.getElementById('lightModeButton');
    if (buttonText.innerHTML === "Light") {
        buttonText.innerHTML = "Dark";

    }

    else {
        buttonText.innerHTML = "Light"
    }



    var footerLight = document.getElementById('footer');
    footerLight.classList.toggle("footer-color");
    footerLight.classList.toggle("footer-color a");




}

// light mode function for my information page

function lightModeInformation() {

    var textInfo = [document.getElementById('textInformation'), document.getElementById('textInformation2'), document.getElementById('h1Information')];
    textInfo[0].classList.toggle("text-when-light");
    textInfo[1].classList.toggle("text-when-light");
    textInfo[2].classList.toggle("text-when-light");

    var element = document.body;
    element.classList.toggle("light-mode");

    var buttonText = document.getElementById('lightModeButton');
    if (buttonText.innerHTML === "Light") {
        buttonText.innerHTML = "Dark";

    }

    else {
        buttonText.innerHTML = "Light"
    }

    var footerLight = document.getElementById('footer');
    footerLight.classList.toggle("footer-color");
    footerLight.classList.toggle("footer-color a");


}

我尝试使用 if 语句,但没有用

【问题讨论】:

标签: javascript html css lightmode


【解决方案1】:

实现此目的的一个好方法是使用类似 localStoragesessionStorage 的变量。当用户关闭选项卡/浏览器时,会话存储将被清除,但 localStorage 将被保留,直到用户手动清除。

在模式之间切换时,您可以执行 localStorage.setItem('mode', 'dark')localStorage.setItem('mode', 'light') 之类的操作,然后在页面加载时您可以再次检查模式并应用它。

类似的东西:

window.addEventListener("load", (event) => {
  let mode = localStorage.getItem('mode')
  if(mode === 'light'){
      lightMode()
  }
});

更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

【讨论】:

    【解决方案2】:

    我建议在localStorage 中保存有关用户是使用亮模式还是暗模式的信息。您可以从来自同一域的每个站点上的 localStorage 访问此变量。如果您不手动删除它,它还会保留会话。

    例如将模式设置为 localStorage.setItem('mode', 'light'); 并像const mode = localStorage.getItem('mode');一样引用它

    查看docs

    【讨论】:

    • 我不确定如何使用 localStorage,因为我还是网络开发的新手
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多