javascript - 从容器中删除(而不是隐藏)许多 div 的溢出,或限制容器的数量?
问题描述
我想制作一个背景,根据容器的大小添加和删除方形 div,这会受到调整窗口大小的影响。
要添加 div,我在此处按照本文中的示例进行操作。但是,调整屏幕大小会继续增加 div 的数量。有没有办法将正方形的数量限制为容器的大小,或者消除溢出?
(我不想简单地 css overflow:hidden 因为这并不能解决十亿个 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>
推荐阅读
- json - 如何从 MediaWiki 外部数据 JSON 中删除密钥?
- pandas - 组和熊猫之间的差异
- javascript - 在 Google 工作表脚本中将时间戳转换为日期
- python - Python从文本文件的列表中删除目录中的文件
- javascript - 从 promise.then / promise.catch 中获取原始函数名
- ios - 如何自动快速记录电话?
- r - 向饼图添加值和百分比
- java - 在控制器中返回错误时,Spring MVC ResponseEntity 始终为空
- html - 如何使下拉菜单看起来好像是从按钮后面出来的?
- api - 在构建 Java GraphQL API 时,如何避免从数据库中过度获取(即仅获取查询中指定的字段)?