首页 > 解决方案 > 它没有一个一个地切换到一个主题,而是以“太阳能”主题结束并且不会改变。有什么问题?

问题描述

这是代码 -

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);
})

它没有一个一个地切换到一个主题,而是以“太阳能”主题结束并且不会改变。有什么问题?

标签: javascripthtmlwebthemes

解决方案


我没有完全理解你的任务,但我认为你需要切换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>


推荐阅读