亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

保存頁面刷新時的切換位置

保存頁面刷新時的切換位置

慕沐林林 2024-01-03 16:45:51
我在本地主機上的 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>使用此代碼在復選框元素后面插入一個元素。


查看完整回答
反對 回復 2024-01-03
  • 1 回答
  • 0 關注
  • 143 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號