我正在尝试做一个按钮来将我的页面转到深色模式,我遇到了问题,当我将我的页面更改为深色模式,然后将其更改为浅色模式时,它只在第一次工作,但我再次尝试将其更改为深色模式,它什么也不做
这是我的darkmode.js
const active = "light";
$("#btn-darkmode").click(function () {
this.active = "dark";
if (this.active === "dark") {
$(".container-fluid").addClass("dark-mode");
console.log("dark");
}
$(this).click(function () {
this.active = "light";
if (this.active === "light")
$(".container-fluid").removeClass("dark-mode");
console.log("light");
});
});
这是我的index.html
<span>Light</span>
<label class="switch">
<input type="checkbox" id="btn-darkmode">
<span class="slider round"></span>
</label>
<span>Dark</span>
更新index.css
.dark-mode {
background-color: black;
color: white;
}
发布于 2020-06-28 09:15:25
我不确定您的代码出了什么问题,但我使用了toggleClass,它正在工作
$('#btn-darkmode').on('click', function(){
$('.container-fluid').toggleClass('dark-mode');
});
.dark-mode {
background-color: black;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<span>Light</span>
<label class="switch">
<input type="checkbox" id="btn-darkmode">
<span class="slider round"></span>
</label>
<span>Dark</span>
</div>
发布于 2020-06-28 09:50:22
有更简单的方法来实现同样的事情,但我修改了您的代码以使其工作。
let active = "light"; /* changing const to let, const means constant so doesn't have to change it's value once its already set */
$("#btn-darkmode").click(function () {
//this.active = "dark"; removed this line, and we'll use the one defined outside this function call
if (active === "light") { /* change dark to -> light makes more sense */
$(".container-fluid").addClass("dark-mode");
active = "dark"; /* add this line to set the new value of the current state */
console.log("dark");
}else if(active === "dark"){ /* you could use only 'else' instead, because there are only two states */
$(".container-fluid").removeClass("dark-mode");
active = "light";
console.log("light");
}
//remove this block because it's a nested event handler function, and it's creating conflicts.
/*$(this).click(function () {
this.active = "light";
if (this.active === "light")
$(".container-fluid").removeClass("dark-mode");
console.log("light");
}); */
});
https://stackoverflow.com/questions/62617079
复制相似问题