调整窗口大小时两div宽度差小于10时d-none类反复切换问题排查
问题原因
你遇到的类反复切换是状态切换导致宽度反向跳变引发的死循环:
- 当差值刚好小于10时,你隐藏文字、显示图标,
rightButtonGroup的宽度会突然大幅缩小 - 缩小后差值立刻超过10,又触发反向逻辑显示文字、隐藏图标,按钮组宽度再次变大,差值回到小于10的区间,由此反复触发切换
修复方案
1. 增加滞后阈值避免临界区反复跳转
新增状态变量记录当前显示模式,设置两个不同的切换阈值,留出缓冲区间避免临界值来回跳:
2. 给resize事件添加防抖,减少不必要的计算触发
修复后JS代码
const props = el => el.getBoundingClientRect(); const right = document.querySelector(".right") const rightButtonGroupWrapper = document.querySelector(".rightButtonGroup"); const allIcons = [...rightButtonGroupWrapper.querySelectorAll("i")]; const allTexts = [...rightButtonGroupWrapper.querySelectorAll(".text-inner")]; // 新增状态变量记录当前模式 let isIconMode = false; // 防抖函数 const debounce = (func, delay = 150) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => func.apply(this, args), delay); } } function handleWidthChange(e) { const rightContainerWidth = props(right).width; const rBtnGrpWidth = props(rightButtonGroupWrapper).width; const diff = rightContainerWidth - rBtnGrpWidth; // 缓冲阈值:小于10切图标模式,大于20才切回文字模式,预留10px缓冲 if (!isIconMode && diff < 10) { isIconMode = true; allIcons.forEach(icon => icon.classList.remove("d-none")); allTexts.forEach(text => text.classList.add("d-none")); } else if (isIconMode && diff > 20) { isIconMode = false; allIcons.forEach(icon => icon.classList.add("d-none")); allTexts.forEach(text => text.classList.remove("d-none")); } } window.addEventListener('resize', debounce(handleWidthChange), true);
你可以根据实际布局调整第二个阈值的大小,只要两个阈值不相等,就不会出现临界区反复切换的问题。
内容的提问来源于stack exchange,提问作者DecPK
相关产品推荐
相关产品推荐

