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

JavaScript战舰游戏开发:如何循环填充#wrapper容器剩余空间

How to Fill #wrapper with .squares Without Overflowing

Hey there! Great start on your Battleship game—learning JS with hands-on projects like this is such a solid way to build skills. Let's fix that loop so it stops automatically the second your #wrapper is full, no more guessing with a hardcoded 250. Here's a straightforward solution:

1. Calculate the Exact Number of Squares That Fit

Instead of guessing how many squares fit, we can calculate it precisely by:

  • Measuring the actual rendered size of one .squares element (since it uses percentage sizing, we need to grab its real on-screen dimensions)
  • Finding the available inner space inside the #wrapper
  • Doing quick math to get total squares per row multiplied by total rows

2. Modified JavaScript Code

Replace your existing loop with this code—comments explain each step:

const body = document.querySelector('body');
const wrapper = document.querySelector('#wrapper')

// Step 1: Create a temporary square to measure its real size
const tempSquare = document.createElement('div');
tempSquare.classList.add('squares');
wrapper.appendChild(tempSquare);
// Grab the actual rendered width/height of the square
const squareWidth = tempSquare.offsetWidth;
const squareHeight = tempSquare.offsetHeight;
wrapper.removeChild(tempSquare); // Clean up the temp element

// Step 2: Get the wrapper's inner available space
// clientWidth/clientHeight excludes padding/border, which is exactly what we need
const wrapperInnerWidth = wrapper.clientWidth;
const wrapperInnerHeight = wrapper.clientHeight;

// Step 3: Calculate how many squares fit in each row and column
const squaresPerRow = Math.floor(wrapperInnerWidth / squareWidth);
const squaresPerColumn = Math.floor(wrapperInnerHeight / squareHeight);
const totalSquares = squaresPerRow * squaresPerColumn;

// Step 4: Loop to create exactly the right number of squares
for (let i = 0; i < totalSquares; i++) {
  let div = document.createElement('div');
  div.classList = 'squares';
  wrapper.appendChild(div);
}

// Rest of your existing code remains the same
const destroyer1 = document.querySelector('#destroyer1');
const destroyer2 = document.querySelector('#destroyer2');
destroyer1.addEventListener("drag", function(event) {}, false);
destroyer1.addEventListener("dragstart", function(event) {}, false);

3. Why This Works

  • Temporary Square: We create and immediately remove a .squares element to get its real rendered dimensions—this avoids issues with percentage-based sizing that might not match raw CSS values.
  • Client Dimensions: wrapper.clientWidth and wrapper.clientHeight give us the space inside the wrapper (excluding its padding and border), which is perfect since you have box-sizing: border-box set globally.
  • Math: Using Math.floor() ensures we don't create partial squares that would overflow the wrapper.

Bonus: Handle Window Resizing (Optional)

If you want the grid to adjust automatically when the window is resized, wrap the square creation code in a function and call it on load and resize:

function fillWrapperWithSquares() {
  // Clear existing squares first
  wrapper.innerHTML = '';
  
  // Same calculation code as before
  const tempSquare = document.createElement('div');
  tempSquare.classList.add('squares');
  wrapper.appendChild(tempSquare);
  const squareWidth = tempSquare.offsetWidth;
  const squareHeight = tempSquare.offsetHeight;
  wrapper.removeChild(tempSquare);

  const wrapperInnerWidth = wrapper.clientWidth;
  const wrapperInnerHeight = wrapper.clientHeight;

  const squaresPerRow = Math.floor(wrapperInnerWidth / squareWidth);
  const squaresPerColumn = Math.floor(wrapperInnerHeight / squareHeight);
  const totalSquares = squaresPerRow * squaresPerColumn;

  for (let i = 0; i < totalSquares; i++) {
    let div = document.createElement('div');
    div.classList = 'squares';
    wrapper.appendChild(div);
  }
}

// Run on page load
fillWrapperWithSquares();

// Run when window resizes
window.addEventListener('resize', fillWrapperWithSquares);

This way, your grid will always fit perfectly no matter how the window size changes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:28:14