首页 > 解决方案 > create markup sections bases on height of divs using jquery

问题描述

I have multiple number of divs with class .row, I want to copy all those divs in sections with respective of their heights , Maximum height for each section should be 1100px, I want to copy all the divs in different sections and if section height reaches 1100 pixel then new section should be created, please see below example:

<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>

In the above example first of all I should get the heights of all divs then I should make the calculation and create sections using jQuery. Let suppose .row1 has 700px height, .row2 is 900px , .row3 is 300px and .row4 is 100px.

So the resultant sections should be generated like this

<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> 

each section should not exceed the height of 1100px. I want to print each section with 1100px on separate Legal Page, I don't want to have more than 1100px section.

I would appreciate if anyone can implement this logic.

标签: javascripthtmljqueryjquery-ui

解决方案


考虑以下。

$(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。如果太高,则将第二部分移至新部分。


推荐阅读