javascript - 如何跨页面设置深色模式,而不是用户必须在每个页面上手动按下它

标签 javascript html

我正在为我的大学项目制作一个网站,需要 5 个页面。

这是我在主页设置深色模式的代码,但是当我进入第二页时我需要手动按下按钮才能获得深色模式 再次打开,而不是维持主页中的信息。

   <img src="DM.png" id="icon">

 </div>


<script type="text/javascript">
    
    var icon = document.getElementById("icon");

    icon.onclick = function() {
        document.body.classList.toggle("darktheme");
        if (document.body.classList.contains("darktheme")) {
            icon.src="LM.png";
        }else
            icon.src="dm.png";

    }
</script>

最佳答案

localStorage 窗口界面的 localStorage 只读属性允许您访问 Document 来源的 Storage 对象;存储的数据跨浏览器 session 保存。

var icon = document.getElementById("icon");
// on page load event we can use previous theme value
window.onload = function() {
    initTheme();
};

function initTheme() {
    const theme = localStorage.getItem('theme');
    if (theme == 'dark') {
        icon.src="LM.png";
    } else {
        icon.src="dm.png";
    }
}

// on icon element click we check the localstorage item 'theme' value to control which theme we should use
icon.onclick = function() {
    localStorage.getItem('theme') === 'dark' ? localStorage.setItem('theme', '') : localStorage.setItem('theme', 'dark');
    initTheme();
}

关于javascript - 如何跨页面设置深色模式,而不是用户必须在每个页面上手动按下它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72372720/

相关文章:

javascript - JS document.getElementById 在按钮点击时执行

html - 在 Outlook 2007/2010/2013 和 Gmail 中重复背景图像

javascript - 如何防止在网站上滚动并仅在 div 之间启用滚动

html - 如何删除<br>之前的空格

javascript - setTimeout 可以使我的循环函数免于被视为无响应吗?

javascript - Twitter Bootstrap Popover 的 Ajax 内容

javascript - 在 div 上添加 css 类

javascript - 如果一个被禁用,两个表单输入可以有相同的名称吗?

javascript - 如何将现有 Dexie 数据库迁移到新的 Dexie 数据库或如何重命名 Dexie 数据库?

javascript - 如何在 HTTP 中使用 Google Chrome 远程调试协议(protocol)?