我在本地主机上的 WordPress 网站上使用 localStorage 进行暗/亮模式切换。一切都按预期工作,但当刷新页面或访问不同页面时,切换位置始终恢复为“亮”。这是我正在使用的代码:(function() { let onpageLoad = localStorage.getItem("theme") || ""; let element = document.body; element.classList.add(onpageLoad); document.getElementById("theme").textContent = localStorage.getItem("theme") || "light";})();function themeToggle() { let element = document.body; element.classList.toggle("dark-mode"); let theme = localStorage.getItem("theme"); if (theme && theme === "dark-mode") { localStorage.setItem("theme", ""); } else { localStorage.setItem("theme", "dark-mode"); } document.getElementById("theme").textContent = localStorage.getItem("theme");}超文本标记语言<div class="slider-div"> <span class="slider-text">Light Mode</span> <label class="switch"> <input type="checkbox" onclick="themeToggle()" id="theme"> <span class="slider round"></span> </label> <span class="slider-text">Dark Mode</span></div>这是我用于复选框的 CSS:.switch { position: relative; display: inline-block; width: 54px; height: 22px;}.switch input { display: none;}.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #CCC; -webkit-transition: .6s; transition: .6s;}.slider:before { position: absolute; content: ""; height: 15px; width: 15px; left: 7px; bottom: 4px; background-color: #FFF; -webkit-transition: .6s; transition: .6s;}input:checked+.slider { background-color: #2196F3;}input:focus+.slider { box-shadow: 0 0 1px #2196F3;}input:checked+.slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px);}/* Rounded sliders */.slider.round { border-radius: 34px;}.slider.round:before { border-radius: 50%;}
1 回答
哔哔one
TA贡献1854条经验 获得超8个赞
您可以设置value
复选框的属性:
document.getElementById("theme").checked = localStorage.getItem("theme") === "dark-mode";
请注意,此代码需要在处理复选框元素后运行。我建议<script>
使用此代码在复选框元素后面插入一个元素。
- 1 回答
- 0 关注
- 81 浏览
添加回答
举报
0/150
提交
取消