javascript - 根据高度将数组划分为多个数组
问题描述
我有很多元素,如 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和元素。现在,我有一页包含所有内容。
解决方案
你应该更精确一点你的问题,但这里有一种可能性(适应你的情况)。
我假设这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)
}
您还可以避免最后一行并将结果存储在一个新的数组中。
推荐阅读
- jquery - 在jQuery中增加字符串日期
- actionscript-3 - adobe animate 虚拟相机无法固定相机
- r - ggplot facet_wrap 仅在顶部和左侧带有标签
- c# - DatagridView 从字典键绑定
- azure-load-balancer - 如何使用 NSG 限制从 Internet 直接访问 Azure Public LoadBalancer 后端池 VM
- mysql - 如何将两个查询与case语句结合起来
- sql - 将这些查询组合成一个返回的函数
- routes - 通过 Rails 路由中的 URL 参数匹配
- flutter - 如何使用 Navigator 移动到有状态页面
- javascript - TypeError:无法读取未定义的属性“映射”-尝试将值映射到卡时