在光和黑暗主题之间切换



好吧,现在我存储用户当前在 localStorage中使用的主题,当页面加载时,我进行检查并显示光或黑暗主题:

var currentTheme = localStorage.getItem('theme-mode');
if (currentTheme !== null && currentTheme === 'theme-dark') {
    $('body').addClass('theme-dark');
    $('#btnChangeTheme').html('Dark Theme: On');
} else {
    $('body').removeClass('theme-dark');
    localStorage.removeItem('theme-mode');
    $('#btnChangeTheme').html('Dark Theme: Off');
}

上面的代码的目的是如何实现,但是我面临的问题是,当用户选择"黑暗主题"时,他们仍然会在页面加载中看到split秒的光主题。有人知道我怎么能解决这个问题,还是应该尝试不同的事情?

而不是使用类更改主题,您可以使用完全不同的CSS。

在服务器上保存2个CSS文件:dark.css,light.css。

在index.html中不要参考其中任何一个。在标题中添加一个脚本标签,该标签将使用正确的CSS添加到页面上的链接,例如:

var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = 'css/dark.css';
    document.head.appendChild(link);

,浏览器将加载CSS

为了避免使用fouc(未经风格的内容的闪光),最好在 <head>中添加内联脚本。但是,慢速网络连接可能会破坏我们的代码。因为在执行$('body')时,<body>可能还不存在。

我认为最好的解决方案是将theme-dark类添加到<html>,因此没有机会选择不存在的元素。为了处理按钮的文本,我们可以使用HTML和CSS使用一些技巧。

<html>
<head>
  <script>
    var currentTheme = localStorage.getItem('theme-mode');
    if (currentTheme !== null && currentTheme === 'theme-dark') {
      $('html').addClass('theme-dark');
    } else {
      $('html').removeClass('theme-dark');
      localStorage.removeItem('theme-mode');
    }
  </script>
  <style>
    html #btnChangeTheme span.light {
      display: inline;
    }
    html #btnChangeTheme span.dark {
      display: none;
    }
    html.theme-dark #btnChangeTheme span.light {
      display: none;
    }
    html.theme-dark #btnChangeTheme span.dark {
      display: inline;
    }
  </style>
</head>
<body>
  <div id="btnChangeTheme">
    <span class="dark">
      Dark Theme: On
    </span>
    <span class="light">
      Dark Theme: Off
    </span>
  </div>
</body>
</html>

最新更新