css 黑暗模式在重新加载时 Flink 白色背景1毫秒

eqzww0vc  于 2023-02-20  发布在  Flink
关注(0)|答案(1)|浏览(156)

我正在尝试在我的应用中添加这个暗模式功能。它使用本地存储来存储用户的偏好,以备将来使用。所以现在的问题是,当暗模式被启用时,页面会因为某种原因而被重新加载,例如,如果用户故意重新加载页面,或提交表单,然后在变黑之前,整个页面上会出现白色背景的 Flink 。它停留了几分之一秒。它看起来很不专业。
还没找到解决的办法,所以请帮帮我。
下面的代码片段在SO中不起作用,因为代码包含localStorage对象。
下面是代码:

const toggleSwitch = document.querySelector('#dark-mode-button input[type="checkbox"]');
const currentTheme = localStorage.getItem('theme');

if (currentTheme) {
    document.documentElement.setAttribute('data-theme', currentTheme);
    if (currentTheme === 'dark') {
            toggleSwitch.checked = true;
    }
}

function switchTheme(e) {
    if (e.target.checked) {
        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem('theme', 'dark');
    }else {        
        document.documentElement.setAttribute('data-theme', 'light');
        localStorage.setItem('theme', 'light');
    }    
}

toggleSwitch.addEventListener('change', switchTheme, false);
:root {
  --primary-color: #495057;
  --bg-color-primary: #F5F5F5;
}

body{
  background-color: var(--bg-color-primary); 
}

[data-theme="dark"] {
  --primary-color: #8899A6;
  --bg-color-primary: #15202B;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
  background-color: #fff;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
<div id="dark-mode-button">
    <input id="chck" type="checkbox">Dark Mode
    <label for="chck" class="check-trail">
      <span class="check-handler"></span>
    </label>
</div>

<table class="table">
    <thead>
      <tr>
          <th>Header 1</th>
          <th>Header 2</th>
          <th>Header 3</th>
      </tr>
    </thead>  
    <tbody>
      <tr>
        <td>Alfreds Futterkiste</td>
        <td>Maria Anders</td>
        <td>Germany</td>
      </tr>
    </tbody>                     
</table>
wydwbb8l

wydwbb8l1#

最理想的方法是在文档的<head>中放置一个小的<script>标签来**阻止页面渲染。这样做渲染器应该停止调用JavaScript解释器,将data-theme属性赋给<html>,然后从剩下的地方继续。给予看:
将此<script>放在<head>内-甚至在<link><style>标记之前:

<head>
  <!-- meta, title etc... -->

  <script>
  // Render blocking JS:
  if (localStorage.theme) document.documentElement.setAttribute("data-theme", localStorage.theme);
  </script>

  <!-- link, style, etc... -->
</head>

然后,在</body>结束标记之前以非渲染阻塞方式使用所有其他脚本:

<!-- other <script> tags here -->

<script>
const toggleSwitch = document.querySelector('#dark-mode-button input[type="checkbox"]');

if (localStorage.theme) {
  toggleSwitch.checked = localStorage.theme === "dark";
}

function switchTheme(e) {
  const theme = e.target.checked ? "dark" : "light";
  document.documentElement.setAttribute("data-theme", theme);
  localStorage.theme = theme;
}

toggleSwitch.addEventListener("change", switchTheme);
</script>

    
<!-- Closing </body> goes here -->

相关问题