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

前端新手求助:实现10x10 WebGrid随机选中与切换功能

解决方案

首先先修正你的HTML结构,所有grid-item都得放在grid-container内部,不然网格布局不会生效:

<div class="grid-container">
  <!-- 这里放100个grid-item -->
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <!-- ... 剩下98个 -->
</div>

然后添加基础CSS样式,实现10x10网格布局,同时区分选中状态:

.grid-container {
  display: grid;
  grid-template-columns: repeat(10, 1fr); /* 10列等宽分布 */
  gap: 2px; /* 网格项之间的间距 */
  width: fit-content;
  margin: 20px auto;
}

.grid-item {
  width: 40px;
  height: 40px;
  background-color: #e0e0e0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.grid-item.selected {
  background-color: #4caf50; /* 选中时用绿色背景区分 */
}

接下来是核心JavaScript逻辑,用Math.random实现你的需求,步骤清晰易懂:

// 获取所有网格项元素
const gridItems = document.querySelectorAll('.grid-item');
// 记录当前选中的项
let currentSelectedItem = null;

// 随机选中网格项的函数
function selectRandomItem() {
  // 先取消之前选中项的状态
  if (currentSelectedItem) {
    currentSelectedItem.classList.remove('selected');
  }

  // 生成0-99的随机索引(100个项的索引从0开始)
  const randomIndex = Math.floor(Math.random() * gridItems.length);
  currentSelectedItem = gridItems[randomIndex];
  // 给新选中项添加样式类
  currentSelectedItem.classList.add('selected');
}

// 页面加载完成后自动触发第一次随机选中
window.addEventListener('DOMContentLoaded', selectRandomItem);

// 给每个网格项绑定点击事件
gridItems.forEach(item => {
  item.addEventListener('click', () => {
    // 只有点击当前选中的项时,才切换到下一个随机项
    if (item === currentSelectedItem) {
      selectRandomItem();
    }
  });
});

关键逻辑说明

  • Math.random()生成0到1之间的随机小数,乘以网格项总数(100)后用Math.floor()取整,就能得到0到99的有效索引,对应100个网格项。
  • 用currentSelectedItem变量记录当前选中项,每次切换前先清除它的选中样式,再给新项添加。
  • 点击事件里做了判断,只有点击当前选中的项才会触发切换,避免误触其他项导致混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:12:34