1

	var grid = document.getElementById("grid");
	var size = 50;

	for (var y = 0; y < size; y++) {
		var currentRow = grid.insertRow(0);
		for (var x = 0; x < size; x++) {
			var currentCell = currentRow.insertCell(-1);
			currentCell.style.height = currentCell.style.width = `calc(100vh / ${size})`;
			currentCell.style.backgroundColor = (x+y)%2 == 0 ? "Blue" : "Red";
		}
	}
body {
	margin: 0;
}

table#grid {
	border-collapse: collapse;
	height:	100%; 
}
<html>
	<body>
		<table id="grid" align="center"></table>
	</body>
</html>

我需要的是一个适合屏幕高度并具有方形单元格的表格。我几乎尝试了所有方法,使用隐藏图像得到了最好的结果。细胞几乎是正方形的,但不足以满足我的需要。当然我不想使用任何绝对间距。事实上,我也想在没有图像的情况下做到这一点,只是简单的 CSS/JavaScript。表的大小将在运行时才知道,但我们假设它是 2 x 2:

<table>
    <tr>
        <td><img src='placeholder.png'></td>
        <td><img src='placeholder.png'></td>
    </tr>
    <tr>
        <td><img src='placeholder.png'></td>
        <td><img src='placeholder.png'></td>
    </tr>
</table>

在 CSS 中

table {
    height: 100%;
}

img {
    height: 100%;
    width: auto;
    visibility: hidden
}

非常感谢任何想法(不太复杂)。

4

1 回答 1

0

你可以使用CSScalc来计算高度和宽度,我不知道它是否正是你想要的,但你可以在这里尝试:

.blue {
  background-color: blue;
}

.red {
  background-color: red; 
}

body {
    margin: 0;
}

td {
  height: calc(100vh / 2);
  width: calc(100vh / 2);
}

table {
    border-collapse: collapse;
}
<table>
    <tr>
        <td class="blue"></td>
        <td class="red"></td>
    </tr>
    <tr>
        <td class="red"></td>
        <td class="blue"></td>
    </tr>
</table>

如果您需要更改网格大小,还可以添加一些 javascript 代码,并计算每个单元格的新高度和宽度。

于 2019-03-10T21:17:49.377 回答