使用jQuery根据div高度自动创建最高1100px的section分页区块
实现逻辑说明
- 核心思路:预先统计所有
.row元素的实际高度,按累加高度不超过1100px的规则分组,每组包裹为一个section插入DOM - 采用
outerHeight(true)计算高度,包含元素的margin、padding、border值,高度计算更准确 - 内置排序逻辑可最大化利用每个section的空间,也可根据需求保留原有row的先后顺序
完整jQuery代码
// 等待所有页面资源加载完成后执行,避免图片、表格未加载导致高度计算错误 $(window).on('load', function() { // 可配置参数 const MAX_SECTION_HEIGHT = 1100; // section最大高度限制 const ROW_PARENT_SELECTOR = 'body'; // 请替换为实际存放.row元素的父容器选择器 // 1. 收集所有row元素及对应高度 const $rows = $('.row'); const rowList = []; $rows.each(function() { rowList.push({ $el: $(this), height: $(this).outerHeight(true) }); // 从原DOM移除,避免重复渲染 $(this).remove(); }); // 可选:按高度降序排列,最大化利用section空间,和示例输出逻辑一致 // 如果需要保留原有row的先后顺序,请注释掉下面这段排序代码 rowList.sort((a, b) => b.height - a.height); // 2. 分组打包到section let currentSection = $('<section></section>'); let currentTotalHeight = 0; rowList.forEach(row => { // 特殊处理:单个row高度超过最大限制,单独分配section if (row.height > MAX_SECTION_HEIGHT) { // 先把之前已填充的section插入父容器 if (currentTotalHeight > 0) { $(ROW_PARENT_SELECTOR).append(currentSection); currentSection = $('<section></section>'); currentTotalHeight = 0; } // 超高元素单独放一个section const singleSection = $('<section></section>').append(row.$el); $(ROW_PARENT_SELECTOR).append(singleSection); return; } // 判断当前section加入当前row后是否超出高度限制 if (currentTotalHeight + row.height <= MAX_SECTION_HEIGHT) { currentSection.append(row.$el); currentTotalHeight += row.height; } else { // 超出限制,先保存当前section,新建section存放当前row $(ROW_PARENT_SELECTOR).append(currentSection); currentSection = $('<section></section>').append(row.$el); currentTotalHeight = row.height; } }); // 3. 把最后剩余的未插入的section加入DOM if (currentTotalHeight > 0) { $(ROW_PARENT_SELECTOR).append(currentSection); } // 可选:注入打印样式,确保每个section单独占一个打印页,适配Legal尺寸打印需求 $('<style>@media print { section { page-break-after: always; } }</style>').appendTo('head'); });
注意事项
- 若需要保留原有row的先后顺序,注释掉排序代码即可
- 如果单个row高度超过1100px,代码会自动为其单独分配section,可根据业务需求提前拆分超高内容避免打印溢出
- 请根据实际页面结构修改
ROW_PARENT_SELECTOR参数,替换为存放所有.row的父容器选择器
内容的提问来源于stack exchange,提问作者web dev
相关产品推荐
相关产品推荐

