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

如何使绿色方块始终居中蓝色方块且不超出Grid网格范围?

解决方案

问题原因与修复思路

  1. 位置偏移问题:原代码中绿色方块仅在#five内定位,移动时直接修改px值导致定位基准混乱。改为基于网格行列索引计算中心位置,确保每次移动都精准落在单元格中心。
  2. 边界溢出问题:通过限制行列索引的范围(0-2,对应3x3网格),阻止方块移出网格。

修改后的完整代码

HTML

<div class="wrapper">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
  <div class="four">Four</div>
  <div id="five">Five</div>
  <div class="six">Six</div>
  <div class="seven">Seven</div>
  <div class="eight">Eight</div>
  <div class="nine">Nine</div>
  <div class="mun"></div> <!-- 将绿色方块移到wrapper下 -->
</div>

CSS

.wrapper {
  display: inline-grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: 100px 100px 100px;
  border: 2px solid black;
  position: relative; /* 让绿色方块相对于网格容器定位 */
}

.one, .two, .three, .four, .five, .six, .seven, .eight, .nine {
  background-color: blue;
  border: 1px solid black;
}

.mun {
  background-color: green;
  width: 35px;
  height: 35px;
  position: absolute;
  /* 初始位置:中间单元格中心 */
  top: calc(1 * 100px + (100px - 35px)/2);
  left: calc(1 * 100px + (100px - 35px)/2);
}

JavaScript

const mun = document.querySelector('.mun');
const cellSize = 100; // 每个网格单元格的尺寸
const munSize = 35; // 绿色方块的尺寸
const gridMaxIndex = 2; // 3x3网格的最大索引(0,1,2)

// 初始位置:中间单元格(行1,列1)
let currentRow = 1;
let currentCol = 1;

function updatePosition() {
  // 计算单元格中心的top和left值
  const top = currentRow * cellSize + (cellSize - munSize) / 2;
  const left = currentCol * cellSize + (cellSize - munSize) / 2;
  mun.style.top = `${top}px`;
  mun.style.left = `${left}px`;
}

function control(e) {
  switch (e.key) {
    case 'ArrowLeft':
      if (currentCol > 0) {
        currentCol--;
        updatePosition();
      }
      break;
    case 'ArrowRight':
      if (currentCol < gridMaxIndex) {
        currentCol++;
        updatePosition();
      }
      break;
    case 'ArrowUp':
      if (currentRow > 0) {
        currentRow--;
        updatePosition();
      }
      break;
    case 'ArrowDown':
      if (currentRow < gridMaxIndex) {
        currentRow++;
        updatePosition();
      }
      break;
  }
}

document.addEventListener('keydown', control);

关键修改说明

  • 定位逻辑优化:将绿色方块移至网格容器下,通过行列索引计算中心位置,彻底解决偏移问题。
  • 边界控制:每次移动前检查行列索引是否在0-2范围内,只有合法才更新位置,避免溢出。
  • 代码可读性提升:用变量明确单元格尺寸、方块尺寸和网格最大索引,方便后续调整网格大小。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:23:17