在浏览器上运行时,下面的开关会在第一次单击时激活/禁用暗模式,但仅在第二次单击时才会选中/取消选中。
**最初我checked
只使用了该属性,后来添加了该checked
属性来尝试解决问题(如您所见 - 它没有帮助)。checked
在 JavaScript仅处理属性的情况下,它的行为也相同。
目的是让它在多页站点中工作(因此参与localStorage
)。
我不明白为什么会这样。
有什么建议么?
all-pages.js:
const htmlTag = document.querySelector('html');
const switchBtn = document.querySelector('.slider');
const darkCheckbox = document.querySelector('.dark-cb');
function darkMode() {
if (localStorage.getItem('dark') == 'true') {
darkCheckbox.checked = true;
darkCheckbox.setAttribute('checked', 'checked');
htmlTag.classList.add('dark');
switchBtn.classList.add('dark');
} else {
darkCheckbox.checked = false;
darkCheckbox.removeAttribute('checked');
htmlTag.classList.remove('dark');
switchBtn.classList.remove('dark');
}
}
switchBtn.addEventListener('click', function() {
localStorage.setItem('dark', htmlTag.className.indexOf('dark') == -1);
darkMode();
});
window.onload = darkMode();
样式.css:
html {
min-height: 100%;
}
.switch {
position: absolute;
top: 10px;
left: 20px;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: skyblue;
-webkit-transition: .4s;
transition: .4s;
}
.slider::before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: #FFFF66;
-webkit-transition: .4s;
transition: .4s;
}
input:checked+.slider {
background-color: darkblue;
}
input:focus+.slider {
box-shadow: 0 0 1000px darkblue;
}
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%;
}
.dark {
filter: invert(1);
}
索引.html:
<html lang="en">
<head>
<link href="./style.css" rel="stylesheet" />
</head>
<body>
<nav id="nav-bar">
<label class="switch">
<input type="checkbox" class='dark-cb'>
<span class="slider round" title="light/dark mode"></span>
</label>
</nav>
<script src="all-pages.js"></script>
</body>
</html>