如何使用div和JS在暗/亮模式之间切换?

时间:2020-10-10 10:40:56

标签: javascript html css

我想将页面中的所有“主题”标签从浅色切换到深色,从深色切换到浅色。

<div theme="light" id="switch-theme" class="switch-btn">

这是我的按钮,单击后应将页面上的每个“主题”标签切换到所需的颜色模式。

我尝试过:

    <div theme="light" id="switch-theme" class="switch-btn" 

onclick="this.setAttribute('theme', this.getAttribute('theme') === 'dark' ? 'light' : 'dark')">

但这只会将按钮切换为黑暗,而不是页面上的每个主题属性。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

要执行此操作,必须将单击处理程序功能添加到所有元素。另外,我建议您不要使用嵌入式点击处理程序功能,而可以使用以下方式将事件附加到addEventListener()上:

//get all the elements with class switch-btn
var btnList = document.querySelectorAll('.switch-btn');
//loop through them
btnList.forEach(function(btn){
  //attach the event to the current element
  btn.addEventListener('click', function(){
    //clear the console
    console.clear();
    //set the attribute
    this.setAttribute('theme', this.getAttribute('theme') === 'dark' ? 'light' : 'dark');
    //test
    console.log(`Element at index ${Array.prototype.slice.call(btnList).indexOf(btn)}, theme ${this.getAttribute('theme')}`)
  });
});
<div theme="light" class="switch-btn">Div 1</div>
<div theme="light" class="switch-btn">Div 2</div>

答案 1 :(得分:0)

这也是基于您的代码一次将主题属性值切换到所有元素的另一种方法:

let btn = document.querySelector("#switch-theme");

btn.addEventListener("click", function() {

  let theme = document.querySelectorAll("[theme]");
  for (let i = 0; i < theme.length; i++) {
    theme[i].setAttribute('theme', theme[i].getAttribute('theme') === 'dark' ? 'light' : 'dark')
  }
});
.switch-btn {
  appearance: button;
  display: inline-block;
}

[theme="dark"] {
  background: black;
  color: white;
}
<div  id="switch-theme" class="switch-btn">Switch theme</div>
<div theme="light"> Theme boxe</div> 
<div theme="light">Theme boxe</div>
<div theme="light"> Theme boxe</div> 
<div theme="light">Theme boxe</div>