javascript - 它没有一个一个地切换到一个主题,而是以“太阳能”主题结束并且不会改变。有什么问题?
问题描述
这是代码 -
const bodyClassList = document.body.classList;
const bodyClass = document.body.className;
const themes = ["light", "solar", "dark"];
themeBtn.addEventListener('click', () => {
themes.forEach(theme => {
bodyClassList.replace(bodyClass, theme);
})
theme = document.body.className;
console.log(theme);
})
它没有一个一个地切换到一个主题,而是以“太阳能”主题结束并且不会改变。有什么问题?
解决方案
我没有完全理解你的任务,但我认为你需要切换body
标签的几个背景颜色类。
我为您做了一个使用运算符在类之间切换的示例switch
,以及来自themes[...]
数组的类索引计数器。
接下来,我清理classList
:
bodyClassList.classList = '';
并添加具有适当索引的类:
bodyClassList.classList.add(themes[index]);
这样的结果有必要吗?
const bodyClassList = document.body;
const themes = ["light", "solar", "dark"];
const themeBtn = document.querySelector('.themeBtn');
let index = 0;
themeBtn.addEventListener('click', () => {
switch (index) {
case 0:
index = 1;
break;
case 1:
index = 2;
break;
case 2:
index = 0;
break;
}
bodyClassList.classList = '';
bodyClassList.classList.add(themes[index]);
})
body {
background-color: white;
}
.light {
background-color: lightgrey;
}
.solar {
background-color: yellow;
}
.dark {
background-color: black;
}
<button class="themeBtn">theme</button>
推荐阅读
- iis - 附加到本地 IIS ASP.Net Core 进程时,Visual Studio 2017 未命中断点
- docker - 如何访问 docker-in-docker 内的企业 docker hub?
- javascript - 仅显示有限数量的包含 HTML 的文本
- c++ - C++ Visual Studio 蓝牙适配器已启用
- python - 为什么 Pip 会忽略已配置的具有嵌套依赖项的存储库?
- fortran - Fortran中带有3个参数的Getarg函数
- r - 在 R 中的多个列中删除组内的 NA
- python - 自定义序列化程序格式
- python - python 3 和 macos 由于 EnvironmentError 无法安装软件包:[Errno 30] 只读文件系统
- angular - 在 IIS 服务器中托管 Ionic 4 和 Angular Wpa SPA