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
.squareselement (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
.squareselement to get its real rendered dimensions—this avoids issues with percentage-based sizing that might not match raw CSS values. - Client Dimensions:
wrapper.clientWidthandwrapper.clientHeightgive us the space inside the wrapper (excluding its padding and border), which is perfect since you havebox-sizing: border-boxset 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
相关产品推荐
相关产品推荐

