我正在使用javascript为我的管理面板创建一个黑暗模式切换,有时当我转到另一个页面时,背景将是白色的瞬间。
有时,当我多次点击它时,复选框会有一点错误。
有谁知道它有什么问题吗?
谢谢!
var mode = "default";
function swapStyleSheet(){
var pagestyle = document.getElementById('pagestyle');
var lightSwitch = document.getElementById('lightSwitch');
if(mode == "default"){
pagestyle.setAttribute('href', '../css/dark.css');
lightSwitch.title = "Turn the lights back on";
mode = "dark";
} else {
pagestyle.setAttribute('href', '../css/light.css');
lightSwitch.title = "Turn the lights off";
mode = "default";
}
}
function save(){
var checkbox = document.getElementById('lightSwitch');
localStorage.setItem('lightSwitch', checkbox.checked);
load();
//might be fixed by turning load() on (fix this later (glitch makes it so css doesnt load for a sec sometimes and shows white background for split second, (removed buttons(also that when you click save whilst its already activated it will deactive).
}
function load(){
var checked = JSON.parse(localStorage.getItem('lightSwitch'));
document.getElementById("lightSwitch").checked = checked;
if (document.getElementById("lightSwitch").checked = checked) {
swapStyleSheet();
}
}
function restore(){
location.reload();
localStorage.clear()
}
load();
CSS in header:
<link rel="stylesheet" type="text/css" id="pagestyle" href="../css/light.css?parameter=1">
HTML checkbox to activate/deactivate the darkmode
Dark mode: <input type="checkbox" id="lightSwitch" onclick="save()" onmousedown="save()">
答案 0 :(得分:0)
你的address
功能有点混乱:
首先,您将load
设置为等于#lightSwitch.checked
,然后再次进行设置:
checked
简化,您的代码执行此操作:
function load(){
var checked = JSON.parse(localStorage.getItem('lightSwitch'));
document.getElementById("lightSwitch").checked = checked;
if (document.getElementById("lightSwitch").checked = checked) {
swapStyleSheet();
}
}
您可能希望在 var x = true/false;
someproperty = x;
if (someproperty = x)
doSomething();
条件之后进行分配,并且if
不应包含作业:
if