【发布时间】:2020-12-29 19:15:14
【问题描述】:
您好,我有 5 个方格,我想给它们随机的左上角位置,但是给它们随机位置可能会产生这样的问题:
这是我的代码:
let container = document.querySelector(".container");
let squares = document.querySelectorAll(".square");
let pageWidth = container.getBoundingClientRect().width;
let pageHeight = container.getBoundingClientRect().height;
let width;
squares.forEach((square) => {
width = Math.floor(Math.random() * 25) + 30;
square.style.width = width + "px";
square.style.height = width + "px";
square.style.position = "absolute";
square.style.top = Math.floor(Math.random() * (pageHeight - 200)) + "px";
square.style.left = Math.floor(Math.random() * (pageWidth - 200)) + "px";
});
.container {
position: relative;
width: 100%;
height: 100vh;
}
.square:nth-child(1) {
background-color: #142bc5;
}
.square:nth-child(2) {
background-color: #37d437;
}
.square:nth-child(3) {
background-color: #c52f14;
}
.square:nth-child(4) {
background-color: #c5149f;
}
.square:nth-child(5) {
background-color: #38c514;
}
<div class="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
我怎样才能避免这个问题?
【问题讨论】:
-
尝试保存所有先前方块的位置和宽度,并在每次迭代时检查当前位置是否与任何先前的位置重叠。如果重叠 -> 重试。
标签: javascript html css position