如何让容器适配屏幕旋转与Resize,同时保留OnShow触发逻辑?
适配容器尺寸的优化方案
步骤1:封装复用逻辑
先把原有的尺寸调整代码抽成独立函数,这样不管是原有触发时机还是屏幕变化时,都能复用同一套逻辑:
// 封装容器尺寸适配函数 function adjustContainerSize() { const container = this.getComponentByName('Container_Name'); const { clientWidth, clientHeight } = document.documentElement; if (clientHeight > clientWidth) { container.set('width', 600); container.set('height', 300); } else { container.set('width', 220); container.set('height', 400); } }
步骤2:保留原有触发逻辑
继续在OnShow、Initialization等时机调用适配函数,注意用call确保函数内this指向正确:
// 在原有触发时机执行适配 adjustContainerSize.call(this);
步骤3:添加屏幕变化监听
给窗口绑定resize和orientationchange事件,同时加上防抖处理(避免窗口调整时频繁执行函数,减少性能损耗):
// 防抖函数:控制函数执行频率 function debounce(func, delay = 200) { let timer; return function() { clearTimeout(timer); timer = setTimeout(() => func.call(this), delay); }; } // 绑定防抖后的适配函数到事件 const debouncedAdjust = debounce(adjustContainerSize.bind(this)); window.addEventListener('resize', debouncedAdjust); window.addEventListener('orientationchange', debouncedAdjust);
完整代码示例
// 封装容器尺寸适配函数 function adjustContainerSize() { const container = this.getComponentByName('Container_Name'); const { clientWidth, clientHeight } = document.documentElement; if (clientHeight > clientWidth) { container.set('width', 600); container.set('height', 300); } else { container.set('width', 220); container.set('height', 400); } } // 防抖函数,避免频繁触发 function debounce(func, delay = 200) { let timer; return function() { clearTimeout(timer); timer = setTimeout(() => func.call(this), delay); }; } // 原有触发时机执行适配 adjustContainerSize.call(this); // 绑定屏幕变化事件 const debouncedAdjust = debounce(adjustContainerSize.bind(this)); window.addEventListener('resize', debouncedAdjust); window.addEventListener('orientationchange', debouncedAdjust);
关键说明
- 函数封装:把尺寸调整逻辑抽成独立函数,避免重复代码,方便多处调用。
- this指向处理:用
call和bind确保函数内的this能正确获取到容器组件,避免事件监听时this指向丢失。 - 防抖处理:窗口调整和屏幕旋转会频繁触发事件,防抖能让函数只在停止操作后执行一次,减少不必要的性能消耗。
内容的提问来源于stack exchange,提问作者alessio capotondi
相关产品推荐
相关产品推荐

