浏览器大小改变时自动调整select的size属性无需刷新页面的jQuery实现问题
解决方案
你目前的代码仅在页面首次加载时执行一次size计算逻辑,窗口 resize 时没有重新触发计算,因此需要将逻辑封装为公共函数,同时监听窗口 resize 事件触发执行,为了避免 resize 高频触发导致性能问题,可添加防抖处理。
修改后的完整JS代码如下:
// 防抖函数,避免resize频繁触发执行 function debounce(func, delay = 200) { let timer = null; return function() { clearTimeout(timer); timer = setTimeout(() => func.apply(this, arguments), delay); } } // 封装更新select size的公共逻辑 function updateSelectSize() { $("select[multiple]").each(function() { let size; if(window.matchMedia("(max-width: 767px)").matches){ // 视口宽度小于768像素 size = Math.round(this.length * 0.75); } else{ size = Math.round(this.length / 5); } // 可自定义最小size,避免选项过少时显示异常,不需要可删除该行 size = Math.max(size, 2); $(this).css("height","100%").attr("size",size); }); } // 页面加载完成后执行一次 $(document).ready(function() { updateSelectSize(); // 监听窗口resize事件触发更新 $(window).on('resize', debounce(updateSelectSize)); });
补充说明
- 代码保留了你原本的尺寸计算逻辑,仅做了表达式简化,不修改最终计算结果
- 防抖延迟默认设为200ms,你可以根据实际需求调整数值
内容的提问来源于stack exchange,提问作者money_kwarta
相关产品推荐
相关产品推荐

