从容器中移除(而不是隐藏)许多div的溢出,或者将数量限制在容器中



我想制作一个背景,根据容器的大小添加和删除方形div,这会受到窗口大小的影响。

为了添加div,我遵循了本文中的示例。但是,调整屏幕大小会继续增加div的数量。有没有办法将正方形的数量限制在容器的大小上,或者消除溢出?

(我不想简单地使用css溢出:隐藏,因为这并不能解决十亿个div相乘的问题。(我是一个绝对的javascript新手,所以请耐心等待!

let contain = document.getElementById("squareContain");
let width = contain.offsetWidth;
let height = contain.offsetHeight;
var containerArea = width * height;
var canAdd = Math.floor(containerArea/1600); //For 40px x 40px squares
function multiplyNode(node, count, deep) {
for (var i = 0, copy; i < count - 1; i++) {
copy = node.cloneNode(deep);
node.parentNode.insertBefore(copy, node);
}
}
$(window).on("resize", function(){
multiplyNode(document.querySelector('.square'), canAdd, false);
}).resize();

编辑jsfiddle

目前您只计算一次适合多少个正方形,但每次窗口大小更改时都需要重新计算:

let contain = document.getElementById("squareContain");
function canAdd()
{
let square = contain.children[0],
cWidth = contain.offsetWidth,
cHeight = contain.offsetHeight,
sWidth = square.offsetWidth,
sHeight = square.offsetHeight;
return Math.floor(cWidth / sWidth) * Math.floor(cHeight / sHeight);
}
function multiplyNode(node, count, deep) {
if (contain.children.length == count)
return;
if (contain.children.length < count)
{
for (var i = 0, copy; i < count - 1; i++) {
copy = node.cloneNode(deep);
node.parentNode.insertBefore(copy, node);
}
}
else
{
while(contain.children.length > count)
{
contain.removeChild(contain.children[contain.children.length -1]);
}
}
}
$(window).on("resize", function(){
multiplyNode(contain.querySelector('.square'), canAdd(), false);
}).resize();
.square_container{
background-color: #ccc;
position: fixed;
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-content: start;
flex-wrap: wrap;
margin: 0 auto;
padding: 0 auto;
}
.square{
width: 40px;
height: 40px;
background-color: blue;
border: 1px solid red;
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="squareContain" class="square_container">
<div class="square"></div><!--...etc...-->
</div>

相关内容

最新更新