You need to enable JavaScript to run this app. 如何实现点击表格单个单元格循环切换白绿黄红四种背景色
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击表格单个单元格循环切换白绿黄红四种背景色

四色循环切换实现方案

你可以通过定义颜色顺序数组,匹配当前类的索引后取模实现循环切换,修改后的完整代码如下:

完整CSS代码

.green {
  background: green;
  color: white;
}
.white {
  background: white;
  color: black;
}
/* 新增黄色、红色对应样式 */
.yellow {
  background: yellow;
  color: black;
}
.red {
  background: red;
  color: white;
}
#sales-list {
  border: 1px solid black;
}
td {
  padding: 10px;
  border: 1px solid black;
}

完整JS代码

// 按切换顺序定义颜色类数组
const colorOrder = ['white', 'green', 'yellow', 'red'];
const cells = document.querySelectorAll("td");

cells.forEach(cell => {
  cell.addEventListener("click", function() {
    // 获取当前颜色类的索引,计算下一个索引,取模实现循环效果
    const currentIdx = colorOrder.indexOf(this.className);
    const nextIdx = (currentIdx + 1) % colorOrder.length;
    this.className = colorOrder[nextIdx];
  });
});

完整HTML代码

<table id="sales-list">
  <tr>
    <td class="white">Row 1 Col 1</td>
    <td class="white">Row 1 Col 2</td>
    <td class="white">Row 1 Col 3</td>
  </tr>
  <tr>
    <td class="white">Row 2 Col 1</td>
    <td class="white">Row 2 Col 2</td>
    <td class="white">Row 2 Col 3</td>
  </tr>
  <tr>
    <td class="white">Row 3 Col 1</td>
    <td class="white">Row 3 Col 2</td>
    <td class="white">Row 3 Col 3</td>
  </tr>
</table>

修改后点击单元格会按白色→绿色→黄色→红色→白色的顺序循环切换背景色,满足评估标记需求。

内容的提问来源于stack exchange,提问作者Chuck Deb Wood

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 05:21:03