繁体   English   中英

暗模式复选框应保存在本地存储中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM