这里有一个指向3个正方形网格3 square grid的链接
这里有一个指向4个正方形网格4 square grid的链接
这里有一个指向5方形网格5 square grid的链接
正如你在图片中看到的,当方格数超过4x4时,网格溢出了容器.请帮我解决这个问题.
以下是该应用程序的HTML、CSS和Java脚本.
function squares() {
const square = document.querySelector('#grid');
const n = prompt("Enter number of squares for the grid");
console.log(n);
const c = document.querySelector("#container");
const x = 400 / n;
c.style.width = (x * n) + 10 + "px";
c.style.height = (x * n) + 10 + "px";
square.style.width = x * n + "px";
square.style.height = x * n + "px";
for (let j = 0; j < n; j++) {
const row = document.createElement("div");
row.style.width = x * n + "px";
row.style.height = x + "px";
for (let i = 0; i < n; i++) {
const sq = document.createElement('div');
sq.style.border = "3px solid black";
sq.style.backgroundColor = "blue";
sq.style.width = x + "px";
sq.style.height = x + "px";
sq.classList.add('row');
row.appendChild(sq);
}
row.classList.add('square');
square.appendChild(row);
}
}
#container {
margin: auto;
padding: 14px 14px 14px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 4px solid black;
border-radius: 10px;
background-color: white;
display: flex;
}
#grid {
flex: 1;
display: flex;
}
<div id="container">
<div id="grid"></div>
</div>
<div id="input_div">
<button id="submit" onclick="squares()">Enter Number of Squares</button>
</div>
我认为问题出在Java脚本代码中,其中需要创建一个名为"row"的div元素,以防止所有正方形占据顶部的一行.我创建了一个名为‘x’的变量,只是为了根据创建的方块数量来保持每个方块的大小.当我在浏览器中判断这个网站时,我发现问题出在每个正方形的尺寸上,因为无论网格和容器的大小如何,它都会集体溢出.请告知是否可以以任何方式完成,以及是否需要创建‘x’.
我知道代码看起来有点复杂.一个更简单、更容易理解的版本如果能像预期的那样运行,将会有很大的帮助.