如何让多个子div适配父div尺寸不溢出?Etch-a-Sketch项目求助
Etch-a-Sketch 网格适配问题解决方案
你的判断没错,固定尺寸确实是问题核心——当用户输入不同的网格数量时,固定的子元素尺寸和容器宽度无法动态匹配,导致布局错乱。以下是具体的修复方案:
核心修改思路
- 动态计算子元素尺寸:根据容器尺寸和用户输入的每行网格数,自动计算每个子元素的宽高,同时扣除margin占用的空间
- 统一容器尺寸基准:给容器设置固定的正方形尺寸(比如500px),确保网格始终是规整的正方形
- 修正类型转换问题:将prompt返回的字符串转为数字,避免字符串拼接导致的计算错误
修改后的完整代码
HTML
<!DOCTYPE html> <html lang="en"> <head> <script src="script.js" defer></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Etch-A-Sketch</title> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } #container { display: flex; flex-wrap: wrap; width: 500px; height: 500px; } </style> </head> <body> <div id="container"></div> </body> </html>
JavaScript
let container = document.getElementById('container'); // 处理用户输入:转为数字,默认值设为16,限制最大100 let squaresPerSide = Number(prompt('Choose a number up to 100 to make a grid with that many squares on each side.')); squaresPerSide = isNaN(squaresPerSide) ? 16 : Math.min(squaresPerSide, 100); function newGrid() { const containerSize = 500; // 容器的固定尺寸 const margin = 1; // 子元素的margin值 // 计算每个子元素的宽高:扣除左右/上下的margin const squareSize = (containerSize / squaresPerSide) - 2 * margin; let totalSquares = squaresPerSide * squaresPerSide; for (let i = 0; i < totalSquares; i++) { let myDivs = document.createElement('div'); // 动态设置子元素样式 myDivs.style.backgroundColor = 'black'; myDivs.style.width = `${squareSize}px`; myDivs.style.height = `${squareSize}px`; myDivs.style.margin = `${margin}px`; // 用this指向当前触发事件的元素,更可靠 myDivs.addEventListener("mouseover", function() { this.style.backgroundColor = "red"; }); container.appendChild(myDivs); } } newGrid();
关键改动说明
- 把内联样式移到CSS中,代码更清晰易维护
- 增加了用户输入的容错处理:非数字输入默认用16,超过100的限制为100
- 动态计算子元素尺寸,确保无论输入多少,子元素都能刚好填满容器
- 事件监听中使用
this代替myDivs,避免闭包导致的元素指向错误
内容的提问来源于stack exchange,提问作者matmm
相关产品推荐
相关产品推荐

