首页 > 解决方案 > 根据高度将数组划分为多个数组

问题描述

我有很多元素,如 p、span、h1、h2。我不知道多少,因为它是动态的。我需要将元素分成一个div高度为 1000px 的元素。所以,我需要根据高度从一个数组创建多个页面。

for (let i = 0; i < items.length; i++) {
  $('.page').append(items[i]);
}

元素示例:items = [<ul class="ul1">..</ul>, <p class="p2">..</p>, <p class="p2">..</p>, <table>...</table>, <p class="p2">..</p>,<p class="p2">..</p>,<p class="p2">..</p>]

items拥有所有 HTML 元素并且它是动态的,可以有 10 或 100 个元素。这个想法是返回page1,page2,page3 ...等,1000px和元素。现在,我有一页包含所有内容。

标签: javascripthtmlarrays

解决方案


你应该更精确一点你的问题,但这里有一种可能性(适应你的情况)。

我假设这items是一个 jQuery 元素数组(所以我在调用.height())......

编辑:您的编辑显示了一组 HTML 元素,您可以将其转换为 jQuery 元素,例如items = items.map(item => $(item))

let pageInd = 1

// loop over each page
while (items.length) {

  let // stores the items of the current page
      curPageItems = []
  ,   // current page height
      height = 0

  // loop over each elements of the current page
  curPageElmts: while (items.length) {

    // get the next element
    const nextElmt = items.shift()

    // update height
    height += nextElmt.height()

    // break loop if the height goes over 1000px
    if (height > 1000) break curPageElmts

    // otherwise add it to the current page
    curPageItems.push(nextElmt)

  }

  // append those items in the corresponding page
  // (jQuery accepts appending arrays of elements)
  $(`.page-${pageInd++}`).append(curPageItems)

}

您还可以避免最后一行并将结果存储在一个新的数组中。


推荐阅读