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

JS表格单元格动态变色游戏:默认红色设置与代码优化

表格变色游戏:默认红色单元格设置与代码优化

一、非随机设置默认红色单元格

你可以提前定义需要默认显示红色的单元格ID列表,在页面加载完成后,遍历这个列表给对应单元格添加红色样式(推荐用CSS类控制,更易维护)。

实现示例

  1. 先定义CSS类:
.red-cell { background-color: red; }
.white-cell { background-color: white; }
  1. 在JS中设置默认红色单元格:
// 自定义需要默认变红的单元格ID
const defaultRedCells = ['cell-0-0', 'cell-1-2', 'cell-2-1'];

window.addEventListener('DOMContentLoaded', () => {
  // 遍历列表,给对应单元格添加红色类
  defaultRedCells.forEach(id => {
    const cell = document.getElementById(id);
    if (cell) cell.classList.add('red-cell');
  });
});

如果不想用CSS类,也可以直接修改元素的style.backgroundColor,但用类的方式更便于后续样式调整。

二、代码优化缩短方案

1. 用事件委托替代逐个绑定onClick

原来给每个单元格手动加onclick属性的方式冗余且不易维护,改成给表格绑定一个点击事件,通过事件目标判断点击的是单元格,统一处理:

<table id="game-table">
  <!-- 无需给每个td加onclick属性 -->
</table>
const table = document.getElementById('game-table');
table.addEventListener('click', (e) => {
  if (e.target.tagName === 'TD') {
    toggleCells(e.target.id); // 调用切换逻辑
  }
});

2. 封装通用的颜色切换逻辑(基于坐标计算)

把单元格ID设计为cell-${行号}-${列号}的格式,通过解析行列数自动计算周围单元格,避免硬编码每个单元格的相邻ID:

function toggleCells(cellId) {
  // 解析当前单元格的行列数
  const [_, row, col] = cellId.split('-').map(Number);
  // 定义需要切换的方向:自身、上、下、左、右
  const directions = [[0,0], [-1,0], [1,0], [0,-1], [0,1]];
  // 假设表格是3行3列,可根据实际修改行列范围
  const maxRow = 2;
  const maxCol = 2;

  directions.forEach(([dr, dc]) => {
    const targetRow = row + dr;
    const targetCol = col + dc;
    // 检查目标坐标是否在表格范围内
    if (targetRow >= 0 && targetRow <= maxRow && targetCol >=0 && targetCol <= maxCol) {
      const targetCell = document.getElementById(`cell-${targetRow}-${targetCol}`);
      if (targetCell) targetCell.classList.toggle('red-cell');
    }
  });
}

3. 动态生成表格(减少HTML代码)

如果表格行数较多,手动写HTML的<td>会很繁琐,用JS动态生成表格:

function generateTable(rows, cols) {
  const table = document.getElementById('game-table');
  for (let r = 0; r < rows; r++) {
    const tr = document.createElement('tr');
    for (let c = 0; c < cols; c++) {
      const td = document.createElement('td');
      td.id = `cell-${r}-${c}`;
      td.classList.add('white-cell'); // 默认白色
      tr.appendChild(td);
    }
    table.appendChild(tr);
  }
}

// 页面加载时生成3x3表格并设置默认红色单元格
window.addEventListener('DOMContentLoaded', () => {
  generateTable(3, 3);
  const defaultRedCells = ['cell-0-0', 'cell-1-2'];
  defaultRedCells.forEach(id => document.getElementById(id)?.classList.add('red-cell'));
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:02:08