打开切换开关后,我想更改背景颜色和文本颜色。 页面刷新时如何保存状态
<script>
document.getElementById("switch1").onclick = function() {
myFunction()
};
function myFunction() {
let color = document.body.style.background;
if (color === 'black') {
document.body.style.background ="white";
document.body.style.color = "black";
} else {
document.body.style.background = "black";
document.body.style.color = "white";
}
}
</script>
<form>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="switch1">
<label class="custom-control-label" for="switch1">Dark Mode</label>
</form>
最佳答案
您可以使用 localStorage
为了这。每次您运行该函数时,我们都会更新存储在本地存储中的一个名为“darkMode”的 key ,然后在重新加载网页时只需检查此 key
片段不适用于 localStorage,因此 here is a CodePen我赶紧演示
document.addEventListener("DOMContentLoaded", function() {
if (localStorage.getItem('darkMode') === 'true') {
// Black Background
document.getElementById("switch1").checked = true;
document.body.style.background = "black";
document.body.style.color = "white";
} else {
// White Background
document.body.style.background = "white";
document.body.style.color = "black";
}
});
document.getElementById("switch1").onclick = function() {
myFunction()
};
function myFunction() {
let color = document.body.style.background;
if (color === 'black') {
localStorage.setItem('darkMode', 'false');
document.body.style.background = "white";
document.body.style.color = "black";
} else {
localStorage.setItem('darkMode', 'true');
document.body.style.background = "black";
document.body.style.color = "white";
}
}
关于javascript - 引导切换开关以在刷新后保持值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461019/