我想这个问题以前有人问过,所以如果我能被重定向到答案(或提供一些建议),我将不胜感激。
所以,下面的代码绘制了一个 15 x 7 的网格,我想要的是它自动调整大小,保持比例,每次我 (a) 调整窗口大小或 (b) 将其加载到平板电脑中或手机。
即屏幕上的结果应该是完整的 15*7 网格。这是代码(我试过 Bootstrap ,但显然没有正确使用它)。 感谢您的帮助。
var stage = document.querySelector("#stage");
var pattern = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
var SIZE = 60;
var SPACE = 0;
var ROWS = pattern.length;
var COLUMNS = pattern[0].length;
for (var row = 0; row < ROWS; row++) {
for (var column = 0; column < COLUMNS; column++) {
//Create a div HTML element called cell
var cell = document.createElement("div");
//Set its CSS class to "cell"
cell.setAttribute("class", "cell");
//Add the div HTML element to the stage
stage.appendChild(cell);
//Make it black if it's a "1"
if (pattern[row][column] === 1) {
cell.style.backgroundColor = "black";
}
//Position the cell in the correct place
//with 10 pixels of space around it
cell.style.top = row * (SIZE + SPACE) + "px";
cell.style.left = column * (SIZE + SPACE) + "px";
}
}
html,
body {
height: 100%;
}
#stage {
position: relative;
height: 100%;
}
.cell {
position: absolute;
width: 60px;
height: 60px;
border: 1px solid gray;
background-color: white;
}
<div class="container">
<div class="row">
<h1>Grid</h1>
<div id="stage"></div>
</div>
</div>
最佳答案
我建议使用带有填充的伪元素来处理具有自动高度的框的纵横比。这是有效的,因为填充百分比是父宽度的百分比,而不是高度。
.cell:before{
content: '';
display: block;
width: 100%;
padding-top: 100%;
}
在您的情况下,您的单元格还需要按百分比而不是 js 中的像素值定位。
fiddle :http://jsfiddle.net/zukrLbqp/1/
另一个提示,与最初的问题有关,但还有其他方法可以使用 css 定位元素,这根本不需要在 js 中进行。如果你想让我了解它是如何工作的,请告诉我,但这里有一个例子:http://jsfiddle.net/eys59y17/
关于javascript - 调整 div 的大小以保持比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136675/