如何通过本地存储将深色模式应用于网站的所有页面? [已关闭]

问题描述 投票:0回答:1

深色模式通过本地存储保存,但不会自动应用于网站的所有页面。如何确保当我选择深色模式时,它会自动应用于网站的所有页面?如何应用本地存储中保存的内容?

let trilho = document.getElementById('trilho');
let body = document.querySelector('body');

// Check local storage for the user's theme preference
const theme = window.localStorage.getItem("theme");

// Set the initial theme based on localStorage
if (theme === "dark") {
    body.classList.add("dark");
    trilho.classList.add("dark"); // Ensure the button reflects dark mode
} else {
    trilho.classList.remove("dark"); // Ensure the button reflects light mode
}

// Add event listener to toggle dark mode
trilho.addEventListener('click', () => {
    trilho.classList.toggle('dark');
    body.classList.toggle('dark');

    // Update localStorage with the current theme
    if (body.classList.contains("dark")) {
        window.localStorage.setItem("theme", "dark");
        trilho.classList.add("dark"); // Dark mode button
    } else {
        window.localStorage.setItem("theme", "light");
        trilho.classList.remove("dark"); // Light mode button
    }
});
javascript html css
1个回答
-2
投票

您可以在“主页”上导入并使用深色模式,然后渲染它并将基本路径更改为打开的页面(因此您不必将深色模式应用于每个页面,并且可能会出现一些错误或更多行要检查)

© www.soinside.com 2019 - 2024. All rights reserved.