我的页面在深色模式下无法正常工作如何解决?



我有这个简单的网站,我需要让它从浅色主题改为深色主题,浅色主题工作得很好,但深色主题只会正确地改变它的按钮,因为当我点击按钮来改变' body ';元素应该把它的类从"light-theme"改为"dark-theme",改为"light-theme - dark-theme";这是HTML'

<body class="light-theme">
<h1>Task List</h1>
<p id="msg">Current tasks:</p>
<ul>
<li class="list">Add visual styles</li>
<li class="list">add light and dark themes</li>
<li>Enable switching the theme</li>
</ul>
<div>
<button class="btn">Dark</button>
</div>
<script src="app.js"></script>
<noscript>You need to enable JavaScript to view the full site</noscript>

Heres CSS

:root {
--green: #00FF00;
--white: #FFFFFF;
--black: #000000;
}
.btn {
position: absolute;
top: 20px;
left: 250px;
height: 50px;
width: 50px;
border-radius: 50%;
border: none;
color: var(--btnFontColor);
background-color: var(--btnBg);
}
.btn:focus {
outline-style: none;
}
body {
background: var(--bg); 
}
ul {
font-family: helvetica;
}
li {
list-style: circle;
}
.list {
list-style: square;
}
.light-theme {
--bg: var(--green);
--fontColor: var(--black);
--btnBg: var(--black);
--btnFontColor: var(--white);
}
.dark-theme{
--bg: var(--black);
--fontColor: var(--green);
--btnBg: var(--white);
--btnFontColor: var(--black);
}

and heres JavaScript

'use strict';
const switcher = document.querySelector('.btn');
switcher.addEventListener('click', function () {
document.body.classList.toggle('dark-theme')
var className = document.body.className;
if(className == "light-theme") {
this.textContent = "Dark";
} else {
this.textContent = "Light";
}
console.log('current class name: ' + className);
});

我试图改变css中的一些东西,但后来发现问题可能在javascript中,但我的代码与课程中的代码完全相同。

当我点击按钮更改" body " "元素应该把它的类从"light-theme"改为"dark-theme",而不是"light-theme - dark-theme">

这确实是真的-你的JS代码只是切换类"dark-theme"和不做任何与"light-theme"类。

因此,一个简单的修复方法是将两个类都切换为 :
switcher.addEventListener('click', function () {
document.body.classList.toggle('dark-theme')
document.body.classList.toggle('light-theme'); // add this line
var className = document.body.className;
if(className == "light-theme") {
this.textContent = "Dark";
} else {
this.textContent = "Light";
}
console.log('current class name: ' + className);
});

但是你可以简化你的代码,因为你真的不需要两个类。如果轻主题是默认的,只需删除light-theme类和它的所有CSS规则,并将其应用于body。当类被设置时,.dark-theme规则将覆盖这些,否则不会。

最新更新