【问题标题】:How do I keep state of dark mode / light mode on my website (using HTML, CSS, JS) when changing between pages?在页面之间切换时,如何在我的网站(使用 HTML、CSS、JS)上保持暗模式/亮模式状态?
【发布时间】:2022-11-10 18:12:39
【问题描述】:

我正在创建一个网站作为前端实践(我是初学者)。我已经想出了如何使用 JS 在两种 css 颜色样式之间切换。但是,当我单击进入新页面时,不会记住上一页的主题,这意味着它会恢复为原始主题。例如,在我的主页上,默认情况下我有深色主题,我单击切换按钮到活动浅色模式,然后它会切换,但是当我单击下一页时,默认情况下是深色模式。我该如何解决?我想我需要将主题的状态存储在可以记住页面状态的地方,但我不知道该怎么做。必要的代码附在下面:

<!DOCTYPE html>
<html>
    <head> 
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">
    </head>

    <body>
    <header>
        <div class="container">
        <img src="paint-brush-icon-10-inverted.png" id = "icon" alt="" style="width: 35px; position:relative; top:20px; left: 20px;">
        <nav>
            <ul>
                <li><a class="navbar"  href="home.html">Home</a></li>
                <li><a class="navbar" href="introduction2.html">Introduction</a></li>
                <li><a class="navbar" href="experience-education2.html">Experience and education</a></li>
                <li><a class="navbar" href="portfolio.html">Portfolio</a></li>
                <li><a class="navbar" href="contactme.html">Contact Me</a></li>

            </ul>
        </nav>

        </div>

    </header>
        <hr>

     // code unimportant here
        
    <script> 
    
        var icon = document.getElementById("icon");
        icon.onclick = function(){
            document.body.classList.toggle("altmode");
                if(document.body.classList.contains("altmode")){
                    icon.src = "paint-brush-icon-10.png";
                    profile.src = "profile-pic (13).png";
                }else {
                    icon.src = "paint-brush-icon-10-inverted.png";
                    profile.src = "profile-pic (12).png";
                }
        }

    </script>    
    </body>
</html>

我不知道如何使页面通信。我试图获取我单击的页面以检查上一页是否具有浅色或深色主题,但我无法弄清楚。

【问题讨论】:

标签: javascript html css


【解决方案1】:

只需使用localStorage。要跨浏览器会话保存它,只需将轻主题设置如下: localStorage.setItem('theme', 'light')。并从您想要的页面中检索它:const theme = localStorage.getItem('theme')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-24
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-06
    • 2022-01-10
    相关资源
    最近更新 更多