首页 > 解决方案 > 从容器中删除(而不是隐藏)许多 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

标签: javascripthtmljquerycss

解决方案


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

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>


推荐阅读