如何在点击事件上添加和删除多个框的背景颜色

问题描述 投票:0回答:1

当我单击一个框时,页面背景应该更改为框的颜色(正在发生),但我想要的是无论我最后单击哪个框,该框的颜色也应该改变。 我还实现了向我单击的框添加颜色,但是当我单击下一个框时,前一个框上的颜色不会被删除。我只想要一个框(最后单击的)有颜色。

let h2 = document.querySelector("h2");
let p = document.querySelector("p");
let boxes = document.querySelectorAll(".box");
let body = document.body;

boxes.forEach((box) => {
  box.addEventListener("click", (e) => {
    let bgColor = e.target.id;
    body.style.backgroundColor = bgColor;

    if (e.target.id === "white" || e.target.id === "yellow") {
      h2.style.color = "black";
      p.style.color = "black";
    } else {
      h2.style.color = "white";
      p.style.color = "white";
    }

    // if(e.currentTarget.id === bgColor){
    //   box.style.backgroundColor = "#343434";
    // }else {
    //   box.style.backgroundColor = bgColor;
    // }
  }, false)
})
#main {
  width: 40%;
  text-align: center;
}

#boxes {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-block: 1.4rem;
  cursor: pointer;
}

.box {
  height: 100px;
  width: 100px;
  border: 2px solid black;
}

#boxes #grey {
  background-color: grey;
}

#white {
  background-color: white;
}

#blue {
  background-color: blue;
}

#yellow {
  background-color: yellow;
}
<div id="main">
  <h2>Color Switcher</h2>
  <div id="boxes">
    <div class="box" id="grey"></div>
    <div class="box" id="white"></div>
    <div class="box" id="blue"></div>
    <div class="box" id="yellow"></div>
  </div>
  <p>Click the boxes to change the background color of the page as box color</p>
</div>

javascript html css dom dom-events
1个回答
0
投票
let h2 = document.querySelector("h2");
let p = document.querySelector("p");
let boxes = document.querySelectorAll(".box");
let body = document.body;
let lastClickedBox = null;

boxes.forEach((box) => {
box.addEventListener("click", (e) => {
  // Remove color from the last clicked box
if (lastClickedBox) {
  lastClickedBox.style.backgroundColor = "";
}

let bgColor = e.target.id;
body.style.backgroundColor = bgColor;

// Set the color for h2 and p based on the clicked box color
if (bgColor === "white" || bgColor === "yellow") {
  h2.style.color = "black";
  p.style.color = "black";
} else {
  h2.style.color = "white";
  p.style.color = "white";
}

// Set background color for the clicked box
e.target.style.backgroundColor = "#343434";

// Update the last clicked box
lastClickedBox = e.target;
}, false);
});
© www.soinside.com 2019 - 2024. All rights reserved.