【问题标题】:How to enable Dark Mode in all pages?如何在所有页面中启用暗模式?
【发布时间】:2017-10-22 05:42:13
【问题描述】:

所以我有一个 JS 脚本,当用户按下显示暗模式的按钮时,页面切换到 dark_theme.css(而不是使用轻模式 css 的 theme.css)并且当用户按下轻模式按钮时切换回 theme.css。所以我的问题是,当用户使用 darm_theme.css 并加载不同的页面或刷新当前页面时,主题会切换回浅色模式。如何以某种方式保存用户的选择/选择?

function swapStyleSheet(sheet){
    document.getElementById('theme').setAttribute('href', sheet);
}
I have one file called theme.css and one more called dark_theme.css
<link id="theme" rel="stylesheet" type="text/css" href="theme.css">
...more html here...
<p><button class="colormode" onclick="swapStyleSheet('dark_theme.css')">Dark Mode</button> <button class="colormode" onclick="swapStyleSheet('theme.css')">Light Mode</button></p>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    为此使用 localStorage:

    function swapStyleSheet(sheet){
      document.getElementById('theme').setAttribute('href', sheet);
      localStorage.setItem("sheet", sheet);
    }
    
    window.onload = _ =>
     swapStyleSheet(
      localStorage.getItem("sheet") || "default.css"
     );
    

    【讨论】:

    • 这确实有效,但仅适用于与 js 和 2 个 CSS 文件位于同一文件夹中的 index.html 和 about.html 页面。它不适用于子文件夹中的其他页面。
    • @apost 那么你需要绝对网址。那不是代码的问题
    • 如何使用绝对 URL?
    【解决方案2】:

    您可以使用 cookie。 (此处的 Cookie 函数:https://stackoverflow.com/a/24103596

    function swapStyleSheet(sheet){
        document.getElementById('theme').setAttribute('href', sheet);
        createCookie ("sheet", sheet);
    }
    document.addEventListener("DOMContentLoaded", function(event) { 
        var item = readCookie ("sheet") || "default.css";
        swapStyleSheet (item);
    });
    

    【讨论】:

      猜你喜欢
      • 2022-06-23
      • 1970-01-01
      • 2019-12-30
      • 2020-01-31
      • 2022-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多