You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击盒子切换页面背景并仅高亮最后点击的盒子

需求实现:点击盒子切换背景色并高亮最后点击的盒子

当前点击盒子时页面背景会切换为对应盒子颜色(已实现),但需要新增功能:最后点击的盒子自身颜色改变,仅保留该盒子的高亮效果,之前点击的盒子取消高亮。

完整实现代码

HTML

<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>

CSS

#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;
  /* 过渡效果让样式变化更平滑 */
  transition: background-color 0.2s ease;
}

/* 定义高亮样式 */
.box.highlight {
  background-color: #343434 !important;
}

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

#white {
  background-color: white;
}

#blue {
  background-color: blue;
}

#yellow {
  background-color: yellow;
}

JavaScript

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;

    // 1. 重置所有盒子样式:移除高亮,恢复原本颜色
    boxes.forEach(item => {
      item.classList.remove("highlight");
      item.style.backgroundColor = item.id;
    });

    // 2. 给当前点击的盒子添加高亮
    e.target.classList.add("highlight");

    // 文字颜色逻辑保持不变
    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";
    }
  }, false)
})

关键改动说明

  • CSS新增.highlight类定义高亮样式,用!important确保优先级覆盖盒子原有颜色
  • 点击事件中先遍历所有盒子,统一重置样式,避免多个盒子同时高亮
  • 给当前点击的盒子单独添加高亮类,实现仅保留最后点击项的高亮效果
  • 可选添加过渡效果,让颜色切换更自然流畅

内容的提问来源于stack exchange,提问作者Sunil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 13:07:52