Zak*_*Zak 4 html javascript css
我正在尝试在我的应用程序中添加此暗模式功能。它使用 localstorage 来存储用户的偏好以供将来使用。所以现在的问题是当启用了暗模式,并且由于某种原因重新加载页面时,同样是用户故意重新加载页面或提交表单,然后页面上到处都是白色背景闪烁,然后变成黑暗的。它停留在几分之一秒。只是看起来不专业。
还没有找到任何解决办法。所以请帮帮我。
附注。下面的代码片段在 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); Run Code Online (Sandbox Code Playgroud)
: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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
通过在文档的内部放置一个小标签来阻止页面呈现是理想的。通过这样做,渲染器应该停止调用 JavaScript 解释器,将属性分配给,然后在剩下的地方继续。试一试:<script><head>data-theme<html>
把它<script>放在里面<head>- 甚至在<link>or<style>标签之前:
<head>
<!-- meta, title etc... -->
<script>
// Render blocking JS:
if (localStorage.theme) document.documentElement.setAttribute("data-theme", localStorage.theme);
</script>
<!-- link, style, etc... -->
</head>
Run Code Online (Sandbox Code Playgroud)
不是吧闭幕前</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 -->
Run Code Online (Sandbox Code Playgroud)