如何使用切换按钮在本地存储中保存 div 状态 (hide/show)

How to save div state (hide/show) in local storage with toggle button

我有一个显示/隐藏 div 部分的开关,一切正常。所以,我在Js中写了一个函数,用于在页面刷新后保存切换状态。切换状态已正确存储,但该部分始终显示,即使将切换保存为关闭也是如此。我不明白我哪里错了,有人帮我吗?

Fiddle: https://jsfiddle.net/snake93/s0rx4ube/4/

function save() {   
    var checkbox = document.getElementById("ck1");
    localStorage.setItem("ck1", checkbox.checked);  
}

var checked = JSON.parse(localStorage.getItem("ck1"));
    document.getElementById("ck1").checked = checked;

$(document).ready(function(){
    $(".switch input").on("change", function(e) {
    const isOn = e.currentTarget.checked;
    
    if (isOn) {
        $(".hideme").show();
    } else {
        $(".hideme").hide();
    }
  });
});
.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
  }
  
  .switch input { 
    opacity: 0;
    width: 0;
    height: 0;
  }
  
  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
  }
  
  .slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
  }
  
  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%;
  }

/*END OF TOGGLE SWITCH*/



.hideme {
  padding:20px;
  background: blue;
  color: white;
  font-weight: 800;
  text-align: center;
}
<!-- jQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<label class="switch">
<input type="checkbox" id="ck1" onchange="save()">
<span class="slider round hide-off"></span>
</label>

<div class="hideme">Please hide me, but bring me back later ;-)</div>

这是因为只有在按下拨动开关时才会检查 isOn 状态。您需要在文档准备好后立即检查 isOn 状态。像这样。

function save() {   
    var checkbox = document.getElementById("ck1");
    localStorage.setItem("ck1", JSON.stringify(checkbox.checked));  
}

function isChecked(isOn) {
    if (isOn === true) {
        $(".hideme").show();
    } else {
        $(".hideme").hide();
    }
}

//for loading
var checked = JSON.parse(localStorage.getItem("ck1"));
    document.getElementById("ck1").checked = checked;

console.log(checked);

$(document).ready(function(){
    isChecked(checked)
    $(".switch input").on("change", function(e) {
    const isOn = e.currentTarget.checked;
    console.log(isOn)
    isChecked(isOn);
  });
});