如何为成对div匹配最大高度并统一设置该高度?
解决跨列配对元素统一高度的问题
问题描述
现有如下HTML结构,需要实现:
- 将左列第一个(对应Tennis)和右列第一个(对应Football)的内容容器高度统一为两者中的最大值
- 将左列第二个(对应Basketball)和右列第二个(对应Swimming)的内容容器高度统一为两者中的最大值
原代码错误地将左列所有容器设为左列内的最大高度,右列同理,不符合跨列配对的需求。
修正后的jQuery代码
$('.TwoColumnUnit').each(function() { // 获取左右列的目标容器集合 const leftBoxes = $(this).find('.TwoColumnUnit_Left .newsLetterDiv > div'); const rightBoxes = $(this).find('.TwoColumnUnit_Right .newsLetterDiv > div'); // 按索引配对处理每一组 leftBoxes.each(function(index) { const leftBox = $(this); const rightBox = rightBoxes.eq(index); // 先重置高度,确保获取真实的自然高度 leftBox.css('height', ''); rightBox.css('height', ''); // 计算当前配对的最大高度 const maxHeight = Math.max(leftBox.height(), rightBox.height()); // 给配对的两个容器设置统一高度 leftBox.css('height', maxHeight + 'px'); rightBox.css('height', maxHeight + 'px'); }); });
代码说明
- 获取配对集合:分别提取左列和右列的目标容器,确保两者按索引一一对应(若数量不一致,代码会自动忽略超出索引的部分)
- 按索引配对处理:通过
each的索引参数,将左列第n个容器和右列第n个容器绑定为一组 - 重置高度:先清空手动设置的高度,保证获取的是元素内容的自然高度
- 设置统一高度:取当前配对容器的高度最大值,同步设置给两个容器
响应式场景补充
如果页面存在响应式布局(比如移动端自动切换为单列显示),建议在窗口尺寸变化时重新执行高度设置逻辑,确保布局适配:
function setPairedHeights() { $('.TwoColumnUnit').each(function() { const leftBoxes = $(this).find('.TwoColumnUnit_Left .newsLetterDiv > div'); const rightBoxes = $(this).find('.TwoColumnUnit_Right .newsLetterDiv > div'); leftBoxes.each(function(index) { const leftBox = $(this); const rightBox = rightBoxes.eq(index); leftBox.css('height', ''); rightBox.css('height', ''); const maxHeight = Math.max(leftBox.height(), rightBox.height()); leftBox.css('height', maxHeight + 'px'); rightBox.css('height', maxHeight + 'px'); }); }); } // 页面加载完成后执行初始化 $(document).ready(setPairedHeights); // 窗口尺寸变化时重新计算高度 $(window).resize(setPairedHeights);
内容的提问来源于stack exchange,提问作者user22708374
相关产品推荐
相关产品推荐

