Class add and remove

此寫法為達成以下目的(常應用於選單收合)

  • A開啟時,點了B,打開B時要順便收起A
  • A開啟時,點了A,要收起A
.box apple
.box orange
.box grape
.box blue
.box gray
.box
 width: 200px
 height: 100px
 background-color: #eee
 text-align: center
 line-height: 100px
 transition-duration: 0.5s
 
.box.teal
 background-color: teal
 color: #fff
const boxes=document.querySelectorAll(".box");

boxes.forEach(box => box.addEventListener("click", checkall)
)

function checkall(){
 const nowTeal=document.querySelector(".teal");
 
 if(nowTeal){
  nowTeal.classList.remove("teal");
 }
 
 if(nowTeal==this){
  this.classList.remove("teal");
 }else{
   this.classList.add("teal");
 }

}