我有一個復選框,可以通過按下它來隱藏頁眉。我還讓它在選中時將狀態保存在localStorage中(這樣它在重新加載頁面后就不會被重置)。但是,即使它在重新加載頁面并從localStorage獲取狀態后顯示為選中,標題也沒有隱藏。有什么方法可以讓它發揮作用嗎?
<div class="new-hide-header"><。 input id="chck" type="checkbox">
< label for="chck" class="check-trail">
<span class="check-handler"/span>> </span>>
</label>
</div>>
<script>/span>
document.getElementById('chck'/span>)。 onclick = function() {
divTest = document.getElementById('ast-desktop-header')。
divTest2 = document.getElementById('ast-mobile-header') 。
var mq = window.matchMedia("(最大寬度:921px)")。
if (mq.matches) {
//視窗寬度小于570px。
if (divTest2.style.display == "none") {
divTest2.style.display = 'block';
} else {
divTest2.style.display = "none" ;
}
}
//window width is more than 570px; }
else {
if (divTest.style.display == "none") {
divTest.style.display = 'block'。
} else {
divTest.style.display = "none" ;
var checkbox = document.getElementById('chck') 。
localStorage.setItem('chck', checkbox.checked)。
}
}
}
</script>
<script>/span>
function load() {
var checked = JSON. parse(localStorage.getItem('chck') )。
document.getElementById("chck").checked = checked;
}
load()。
</script>
uj5u.com熱心網友回復:
在load()
Stack代碼段不提供對localStorage的訪問,也沒有提供標題html,所以下面是一個簡化的例子
。const chckbox = document. getElementById('chck'/span>)
chckbox.onclick = function(/span>) {
const isChecked = this.checked。
console.log('isChecked ='/span>, isChecked)。
}
function load() {
chckbox.checked = true。
chckbox.onclick()。
}
load()
< input type="checkbox" id="chck"> /span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321677.html
標籤:
