我正在尝试在我的应用程序中添加此暗模式功能。它使用本地存储来存储用户的偏好以供将来使用。所以现在的问题是当暗模式启用时,页面由于某种原因被重新加载,例如。如果用户故意重新加载页面或提交表单,那么在页面变暗之前,整个页面都会出现白色背景闪烁。它停留了几分之一秒。只是看起来不专业。
还没有找到任何解决方案。所以请帮帮我。
PS。下面的代码片段在 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>
最佳答案
最好是 阻止页面渲染通过放置一个小的 <script>
<head>
内的标签您的文档。通过这样做,渲染器应该停止调用 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 -->
关于javascript - 黑暗模式在重新加载时闪烁白色背景一毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63033412/