窗口Resize适配问题:按钮显隐与窗口缩放联动失效(兼容旧浏览器)
解决窗口Resize与按钮显隐联动的兼容方案
嘿,你的核心交互逻辑已经跑通了,问题就出在窗口尺寸变化时,之前初始化的宽度值没跟着更新,而且没考虑到当前已经激活(展开按钮)的元素状态,导致适配和联动失效。下面给你一个兼容老旧浏览器的修复方案,不用flex或calc也能搞定。
问题根源拆解
你只在页面加载时获取了centerWidth1和centerWidth2,但窗口resize后,#wrap的宽度变了,这两个变量还是旧值,自然没法让元素适配新尺寸。而且resize时你没区分哪个.center是处于“缩窄显示按钮”的状态,直接统一设置宽度会破坏当前的交互状态。
具体修复步骤
- 把宽度计算封装成可复用函数:不管是初始化还是resize,都能快速获取最新的宽度值
- 在resize事件中更新状态:先刷新宽度变量,再判断哪个元素是当前激活的,分别给它和其他元素设置对应的新宽度
- 优化动画队列:每次执行动画前先停止之前的动画,避免resize频繁触发时出现动画堆积的问题
修复后的完整代码
HTML(和原代码一致)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div id="wrap"> <div class="row"> <div class="center">center</div> <div class="right">right</div> </div> <div class="row"> <div class="center">center</div> <div class="right">right</div> </div> </div>
CSS(和原代码一致)
#wrap { position: relative; margin: 20px auto; width: 80%; background-color: red; } .row { position: relative; height: 30px; margin-bottom: 10px; } .center { float: left; min-height: 30px; line-height: 30px; display: inline-block; text-align: center; background-color: blue; } .right { float: left; width: 50px; height: 30px; line-height: 30px; display: inline-block; text-align: center; margin-left: 5px; border: 0; background-color: grey; display: none; }
JavaScript(修改后的核心逻辑)
var centerWidth1, centerWidth2; // 封装宽度计算函数,初始化和resize都能用 function updateCenterWidths() { var wrapWidth = $('#wrap').width(); centerWidth1 = wrapWidth; centerWidth2 = wrapWidth - 55; // 50是按钮宽度+5px间距 // 更新所有.center的宽度:判断哪个是激活状态(对应.right显示) $('.center').each(function() { var $this = $(this); if ($this.siblings('.right').is(':visible')) { $this.stop(true, true).css('width', centerWidth2); } else { $this.stop(true, true).css('width', centerWidth1); } }); } // 初始化 $(function() { updateCenterWidths(); // 窗口Resize事件修复 $(window).resize(function() { updateCenterWidths(); }); // 显示按钮逻辑 $(".center").click(function(e) { e.stopPropagation(); var $this = $(this); // 停止之前的动画,避免冲突 $this.stop(true, true).animate({ width: centerWidth2 }, 400); $('.center').not(this).stop(true, true).animate({ width: centerWidth1 }, 400); $this.siblings(".right").delay(400).fadeIn("slow"); $('.center').not(this).siblings(".right").fadeOut(0); }); // 点击外部隐藏按钮逻辑 $(document).click(function() { $('.right').fadeOut(200); $('.center').stop(true, true).delay(200).animate({ width: centerWidth1 }, 400); }); });
关键修改说明
- 封装
updateCenterWidths()函数:每次窗口尺寸变化时,都会重新计算#wrap的宽度,更新centerWidth1和centerWidth2,同时根据每个.right的显示状态,给对应的.center设置正确的宽度,保证联动效果。 - 添加
stop(true, true):停止元素上所有未完成的动画,并直接跳转到动画结束状态,避免resize频繁触发时动画队列堆积,导致页面卡顿或状态错乱。 - DOM加载完成后初始化:把初始化代码放在
$(function(){})里,确保DOM加载完成后再执行,避免获取不到#wrap的宽度。
这样修改后,不管窗口怎么调整,已经激活的元素会保持缩窄状态适配新宽度,未激活的元素也会恢复到新的满宽状态,完美解决联动问题,同时兼容老旧浏览器。
内容的提问来源于stack exchange,提问作者Nrc
相关产品推荐
相关产品推荐

