如何让Etch-A-Sketch网格总尺寸不随内部div数量变化?
Etch-A-Sketch 网格尺寸固定问题修复
问题描述
我正在进行The Odin Project的Etch-A-Sketch模块开发,目前除了输入新的边长方块数量后,网格总尺寸无法保持固定外,其余功能均正常运行。我尝试修改makeRows函数中的div内联样式,但未取得效果,恳请提供技术帮助。
现有代码
JavaScript
const container = document.getElementById("container"); const button = document.querySelector("input"); button.addEventListener('click', ()=> { numOfSquares(); }) function numOfSquares() { if (button.value === "number of squares") { let newNumPerRow = prompt("how many squares per side would you like?", ""); let parse = parseInt(newNumPerRow); makeRows(parse); } } function hoverColor() { let items = document.querySelectorAll('.gridItems'); items.forEach(item => { item.addEventListener('mouseover', () => { item.style.backgroundColor = 'orange'; }); }); } function clearGrid() { const gridArray = Array.from(container.childNodes); gridArray.forEach(element => { container.removeChild(element); }) } function makeRows (numberPerRow) { clearGrid(); const total = (numberPerRow * numberPerRow) + numberPerRow; const box = numberPerRow + 1; for (i=0; i < total; i++) { const div = document.createElement('div'); container.appendChild(div).className = "gridItems"; if (i % box === 0) { div.style.cssText = "border: 0; height: 0; width: 100%"; } else { div.style.cssText = "border: 1px solid black; height: 25px; width: 25px"; } } hoverColor(); } makeRows(16);
CSS
* { box-sizing: border-box; } #container { display: flex; flex-wrap: wrap; justify-content: center; }
HTML
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Etch-A-Sketch Project</title> <link rel="stylesheet" href="style.css"> <script src="index.js" defer></script> </head> <body> <input type="button" value="number of squares"> <div id="container"> </div> </body> </html>
问题分析
- 当前每个方块固定25px宽高,数量增加时总尺寸必然随内容扩展,无法保持固定;
- 用额外空div实现换行的方式冗余且易出错,增加不必要的DOM元素;
- 容器未设置固定尺寸,会随内部方块自动拉伸。
修复方案
步骤1:给容器设置固定尺寸
修改CSS,给容器添加固定宽高,锁定网格总大小:
* { box-sizing: border-box; } #container { display: flex; flex-wrap: wrap; width: 400px; /* 固定宽度 */ height: 400px; /* 固定高度 */ margin: 20px auto; /* 居中显示 */ }
步骤2:动态计算方块尺寸
在makeRows函数中,根据每行方块数量计算单个方块的尺寸,确保刚好填满容器(减去边框宽度,因为box-sizing: border-box会将边框包含在尺寸内):
function makeRows (numberPerRow) { clearGrid(); const squareSize = (400 / numberPerRow) - 2; const totalSquares = numberPerRow * numberPerRow; for (let i=0; i < totalSquares; i++) { const div = document.createElement('div'); div.className = "gridItems"; div.style.cssText = `border: 1px solid black; height: ${squareSize}px; width: ${squareSize}px;`; container.appendChild(div); // 直接给新元素绑定hover事件,避免重复查询DOM div.addEventListener('mouseover', () => { div.style.backgroundColor = 'orange'; }); } }
步骤3:优化其他功能
- 简化清空网格的函数:
function clearGrid() { container.innerHTML = ""; }
- 增加输入验证,防止无效值:
function numOfSquares() { let newNumPerRow = prompt("请输入每行的方块数量:", ""); let parse = parseInt(newNumPerRow); if (!isNaN(parse) && parse > 0) { makeRows(parse); } else { alert("请输入一个有效的正整数!"); } }
修改后的完整代码
JavaScript
const container = document.getElementById("container"); const button = document.querySelector("input"); button.addEventListener('click', ()=> { numOfSquares(); }) function numOfSquares() { let newNumPerRow = prompt("请输入每行的方块数量:", ""); let parse = parseInt(newNumPerRow); if (!isNaN(parse) && parse > 0) { makeRows(parse); } else { alert("请输入一个有效的正整数!"); } } function clearGrid() { container.innerHTML = ""; } function makeRows (numberPerRow) { clearGrid(); const squareSize = (400 / numberPerRow) - 2; const totalSquares = numberPerRow * numberPerRow; for (let i=0; i < totalSquares; i++) { const div = document.createElement('div'); div.className = "gridItems"; div.style.cssText = `border: 1px solid black; height: ${squareSize}px; width: ${squareSize}px;`; container.appendChild(div); div.addEventListener('mouseover', () => { div.style.backgroundColor = 'orange'; }); } } makeRows(16);
CSS
* { box-sizing: border-box; } #container { display: flex; flex-wrap: wrap; width: 400px; height: 400px; margin: 20px auto; }
HTML
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Etch-A-Sketch Project</title> <link rel="stylesheet" href="style.css"> <script src="index.js" defer></script> </head> <body> <input type="button" value="调整方块数量"> <div id="container"> </div> </body> </html>
效果说明
修改后,无论输入多少个方块数量,网格总尺寸都会保持400px×400px不变,每个方块自动调整大小填满容器,hover变色功能正常运行。
内容的提问来源于stack exchange,提问作者MaxRat
相关产品推荐
相关产品推荐

