jQuery设置同行元素等高在窗口resize时不生效如何解决
问题原因
- 第一次执行等高逻辑后,你已经给所有
.item设置了固定高度,后续resize时读取的是已经被固定的高度值,无法获取窗口缩放后内容实际撑开的高度 - 高度计算逻辑有误:没有按
.wrapper分组计算组内最高高度,遍历逻辑也无法正确拿到当前行所有元素的最大高度 - resize事件触发频率极高,未做防抖处理也可能导致执行异常、页面卡顿
修复方案
优先推荐纯CSS方案(无需JS)
你已经给.item设置了inline-flex,只需要给父容器.wrapper加flex布局属性,就能原生实现等高,性能远好于JS方案:
.wrapper{ margin-bottom:30px; display: flex; flex-wrap: wrap; /* 有换行需求时保留该属性 */ align-items: stretch; } .wrapper .item { flex: 0 0 30%; background: #ddd; margin-right: 1%; }
若必须使用JS实现,修复后代码如下:
jQuery( document ).ready(function($) { // 防抖处理,避免resize频繁触发导致卡顿 function debounce(func, wait = 100) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); } } function eq_height(){ // 先重置所有item高度为auto,恢复内容原生高度再计算 $('div.item').height('auto'); // 按wrapper分组计算,每组独立设置等高 $('.wrapper').each(function() { let maxHeight = 0; const $items = $(this).find('.item'); // 首次遍历拿到组内最大高度 $items.each(function() { const currentHeight = $(this).outerHeight(); if (currentHeight > maxHeight) { maxHeight = currentHeight; } }); // 统一设置组内所有元素高度 $items.height(maxHeight); }); } eq_height(); // 绑定防抖后的resize事件 $(window).resize(debounce(eq_height)); });
内容的提问来源于stack exchange,提问作者Maruf Sarkar
相关产品推荐
相关产品推荐

