簡體   English   中英

如何跨頁面設置暗模式,而不是用戶必須在每個頁面上手動按下它

[英]How do i set dark mode accross pages instead of user having to manually press it on every single page

我正在為我的 Uni 項目制作一個需要 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 對象; 存儲的數據跨瀏覽器會話保存。

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();
}

您唯一需要做的就是將主題存儲在document.cookie中。 這是您需要的代碼:

<img src="DM.png" alt="OPS!" id="icon" />

<script type="text/javascript">

    var icon = document.getElementById("icon");
    //Theme saves here
    var theme = /theme/.test(document.cookie) ? document.cookie.split("theme=")[1].split(';')[0] : "whitetheme";

    //Load theme at first
    window.onload = function () {
        if (theme == "darktheme") {
            document.body.classList.add("darktheme");
        }
    };

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

        //Save theme and expire time
        var date = new Date();
        document.cookie = "theme=" + theme + ";expires=" + date.setTime(date.getTime() + (365*24*60*60*1000)) + ";path=/"
    }

</script>

有一個設置頁面,用戶可以在其中選擇他們喜歡的設置並將其保存在數據庫中。

然后在他們登錄時將其加載到會話變量上。

如果他們在登錄時更改該會話變量,請更新該會話變量。

要么有一個單獨的設置頁面,要么將其包含在他們的個人資料頁面中。 個人資料頁面是他們可以更改電子郵件、密碼、頭像等的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM