自定义jQuery窗口resize逻辑仅在视口宽度为偶数时生效问题求助
问题分析与解决方案
核心问题
你当前的判断逻辑存在根本性错误:你拿导航栏(.wp-container-5)的宽度直接和父容器(.wp-container-6)宽度对比,但导航栏换行的实际触发条件是logo容器宽度 + 导航栏宽度 > 父容器宽度,而非导航栏自身宽度超过父容器。这是导致特定宽度区间内判断混乱的主要原因。
另外,浏览器的亚像素渲染会让元素宽度出现小数(比如1377.5px),当窗口宽度在奇偶值间切换时,计算出的宽度会在临界值附近波动;再加上resize事件高频触发,就会导致类名频繁被添加/移除,出现布局跳变。
修复步骤
- 修正判断逻辑:计算logo容器与导航栏的总宽度,再和父容器宽度对比
- 添加防抖函数:避免
resize事件高频触发导致的重复计算 - 处理亚像素精度:用
Math.round()对宽度取整,消除小数干扰
最终代码
// 防抖函数:降低resize事件触发频率 function debounce(func, wait = 100) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; } function checkNavWrap() { $('.wp-container-5').each(function() { const $nav = $(this); const $parent = $nav.parent('.wp-container-6'); const $logo = $parent.find('.logo-container'); // 取整消除亚像素计算误差 const navWidth = Math.round($nav.outerWidth()); const logoWidth = Math.round($logo.outerWidth()); const parentWidth = Math.round($parent.width()); // 判断logo+导航栏的总宽度是否超出父容器 if (navWidth + logoWidth > parentWidth) { $nav.addClass('wrapped'); } else { $nav.removeClass('wrapped'); } }); } // 页面加载时初始化执行 checkNavWrap(); // 绑定防抖后的resize事件 $(window).resize(debounce(checkNavWrap));
额外说明
- 用
outerWidth()替代width(),确保计算包含导航栏的padding和border(若存在),结果更准确 - 如果logo容器带有margin,需改用
outerWidth(true)来包含margin值,保证总宽度计算无误 - 防抖时间可根据需求调整,100ms是兼顾响应速度与性能的适中值
内容的提问来源于stack exchange,提问作者Nellie
相关产品推荐
相关产品推荐

