使用 jquery 根据 div 的高度创建标记部分

Posted

技术标签:

【中文标题】使用 jquery 根据 div 的高度创建标记部分【英文标题】:create markup sections bases on height of divs using jquery 【发布时间】:2021-10-20 01:03:59 【问题描述】:

我有多个具有 .row 类的 div,我想将所有这些 div 复制到具有各自高度的部分中,每个部分的最大高度应为 1100px,我想复制不同部分中的所有 div,如果部分高度达到 1100 像素,则应创建新部分,请参见以下示例:

<div class="row row1">
     <p>some html tables and paragraphs here </p>
</div>
<div class="row row2">
     <p>some html tables and paragraphs here </p>
</div>
<div class="row row3">
     <p>some html tables and paragraphs here </p>
</div>
<div class="row row4">
     <p>some html tables and paragraphs here </p>
</div>

在上面的例子中,首先我应该得到所有 div 的高度,然后我应该使用 jQuery 进行计算并创建部分。 假设 .row1 的高度为 700px,.row2 的高度为 900px,.row3 的高度为 300px,.row4 的高度为 100px。

所以结果部分应该像这样生成

<section>
     <div class="row row1">
         <p>some html tables and paragraphs here </p>
    </div>
    <div class="row row3">
         <p>some html tables and paragraphs here </p>
    </div>
    <div class="row row4">
         <p>some html tables and paragraphs here </p>
    </div>
</section> 

<section>
    <div class="row row2">
         <p>some html tables and paragraphs here </p>
    </div>
</section> 

每个部分的高度不应超过 1100 像素。 我想在单独的法律页面上打印 1100 像素的每个部分,我不想有超过 1100 像素的部分。

如果有人能实现这个逻辑,我将不胜感激。

【问题讨论】:

未指定这些div的个数,可能只有一个,也可能是15加 请说明如何添加新部件。基本上,您将获得sectionheight,如果添加另一个元素使其超过阈值,您将创建一个新的section 并附加到它。请提供一个最小的、可重复的示例:***.com/help/minimal-reproducible-example 【参考方案1】:

考虑以下内容。

$(function() 
  function makeSection() 
    return $("<section>").insertAfter($("section:last"));
  

  function checkHeight(a, b, h) 
    if (h == undefined) 
      h = 1100;
    
    var r = a + b;
    return r > h;
  

  $("section:first .row").each(function(i, el) 
    var t = $("section:first .row").length;
    if (i < t) 
      if (checkHeight($(el).height(), $(el).next().height())) 
        var nextSection = makeSection();
        nextSection.append($(el).next().detach());
      
    
  );
);
section 
  border: 1px solid #999;
  padding: 3px;


section .row 
  border: 1px solid #ccc;
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<section>
  <div class="row row1" style="height: 700px;">
    <p>Item 1</p>
  </div>
  <div class="row row2" style="height: 900px;">
    <p>Item 2</p>
  </div>
  <div class="row row3" style="height: 300px;">
    <p>Item 3</p>
  </div>
  <div class="row row4" style="height: 100px;">
    <p>Item 4</p>
  </div>
</section>

在这里您可以看到我们有一些较小的辅助函数。 checkHeight 将计算组合高度值。如果它们小于阈值 h(默认为 1100),则返回 false。如果超过阈值,则返回true

然后您可以迭代每一行并从每一行获取height。 1 & 2, 2 & 3, 3 & 4。如果太高,则将第二部分移至新部分。

【讨论】:

这对我不起作用,如果我增加了第一部分中的项目数量,它会超过限制 1100。@Twisty

以上是关于使用 jquery 根据 div 的高度创建标记部分的主要内容,如果未能解决你的问题,请参考以下文章

当DIV的高度由jQuery的浏览器高度定义时,如何根据内容增加DIV的高度?

Div在加载时滚动到底部

如何通过JQuery将DIV的滚动条滚动到指定的位置

CSS 根据 jQuery 的宽度百分比设置高度

JQuery - 查找 div 的高度然后创建循环以覆盖 div

jQuery动态改变元素高度