[英]Dark mode checkbox should be saved in local storage
我正在嘗試在我的網站上實現暗模式 - 亮模式切換器。 我對 JS 真的一無所知,但我玩弄了我在網上找到的代碼片段,並把一些類似的東西放在一起。
到目前為止我所擁有的: - 我在 CSS 中有兩組 colors,我可以使用導航欄中的復選框在它們之間切換。 - 我還發現了如何在本地存儲復選框的 state,因此如果我打開暗模式然后導航到另一個頁面,該復選框仍處於選中狀態。
問題是每次我導航到另一個頁面時,復選框首先被取消選中,然后它意識到它必須被選中並且它會自動檢查自己。 但這需要時間,甚至還有一個 animation 這有點煩人,因為如果我在一個頁面上檢查它,我希望在所有其他頁面上默認檢查它,直到我將其關閉。
這是一個可以更好地解釋它的視頻: https://drive.google.com/file/d/1y48yh1h1bGM6abrthVmtUD8azVuDG4yE/view?usp=sharing
任何幫助將不勝感激,因為我真的不知道這里發生了什么:D
// DARK MODE SWITCHER
var checkbox = document.querySelector('input[name=mode]');
checkbox.addEventListener('change', function() {
if(this.checked) {
trans()
document.documentElement.setAttribute('data-theme', 'dark')
} else {
trans()
document.documentElement.setAttribute('data-theme', 'light')
}
})
let trans = () => {
document.documentElement.classList.add('transition');
window.setTimeout(() => {
document.documentElement.classList.remove('transition');
}, 1000)
}
// SAVE DARK MODE CHECKBOX STATE IN LOCAL STORAGE
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
$checkboxes = $("#checkbox-container :checkbox");
$checkboxes.on("change", function(){
$checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
// On page load
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
jsfiddle 解決方案:
https://jsfiddle.net/zhbo40ma/
您需要在頁面加載時設置主題:
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
if($('#'+key).attr('name') == 'mode') {
if(value) {
trans();
document.documentElement.setAttribute('data-theme', 'dark')
}
else {
trans();
document.documentElement.setAttribute('data-theme', 'light')
}
}
});
不要忘記在頁面加載 function 之前寫你的trans()
function 因為你用let
聲明它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.