如何在JavaScript中持续返回屏幕宽度/高度?
纯JavaScript实现持续获取屏幕宽度的方案
要实现持续获取屏幕宽度并配合响应式布局,以下是几种可行的方案,从基础到优化版本都有覆盖:
1. 基础Resize事件监听
直接监听window的resize事件,每次触发时获取当前屏幕宽度。适合简单场景,但需注意事件触发频率较高。
function trackScreenWidth(callback) { // 页面加载时先执行一次,确保初始宽度正确 callback(window.innerWidth); // 监听窗口大小变化 window.addEventListener('resize', () => { callback(window.innerWidth); }); } // 使用示例 trackScreenWidth(width => { console.log('当前屏幕宽度:', width); // 这里编写你的响应式布局逻辑 if (width < 768) { document.body.style.padding = '10px'; } else { document.body.style.padding = '20px 50px'; } });
2. 防抖优化版本
由于resize事件在窗口拖动时会频繁触发,可能导致性能问题,加入防抖函数可以限制回调的执行频率,平衡响应速度与性能。
// 防抖工具函数:事件停止触发delay毫秒后才执行回调 function debounce(func, delay = 200) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(this, args), delay); }; } function trackScreenWidthWithDebounce(callback, delay = 200) { callback(window.innerWidth); const debouncedCallback = debounce(callback, delay); window.addEventListener('resize', () => { debouncedCallback(window.innerWidth); }); } // 使用示例 trackScreenWidthWithDebounce(width => { console.log('防抖后屏幕宽度:', width); const container = document.getElementById('content-container'); container.style.columnCount = width < 600 ? 1 : width < 1000 ? 2 : 3; }, 300);
3. 结合媒体查询(与CSS断点同步)
如果需要和CSS的响应式断点保持一致,可以使用window.matchMedia监听媒体查询变化,直接关联到预设的断点逻辑,更便于维护。
// 定义与CSS一致的断点 const breakpoints = { mobile: '(max-width: 575px)', tablet: '(min-width: 576px) and (max-width: 991px)', desktop: '(min-width: 992px)' }; function trackBreakpoints(callback) { // 初始获取当前状态 const currentWidth = window.innerWidth; let currentBreakpoint = currentWidth < 576 ? 'mobile' : currentWidth < 992 ? 'tablet' : 'desktop'; callback(currentWidth, currentBreakpoint); // 为每个断点注册监听 Object.entries(breakpoints).forEach(([name, query]) => { const mediaQuery = window.matchMedia(query); mediaQuery.addEventListener('change', () => { const newWidth = window.innerWidth; const newBreakpoint = newWidth < 576 ? 'mobile' : newWidth < 992 ? 'tablet' : 'desktop'; callback(newWidth, newBreakpoint); }); }); } // 使用示例 trackBreakpoints((width, breakpoint) => { console.log(`当前宽度: ${width}, 设备类型: ${breakpoint}`); const nav = document.getElementById('main-nav'); if (breakpoint === 'mobile') { nav.classList.add('mobile-menu'); nav.classList.remove('desktop-menu'); } else { nav.classList.add('desktop-menu'); nav.classList.remove('mobile-menu'); } });
注意事项
- 移除监听:当不需要再追踪宽度时,记得移除事件监听,避免内存泄漏。比如保存监听函数的引用,后续调用
window.removeEventListener('resize', 引用)。 - 初始执行:所有方案都先执行一次回调,确保页面加载时就能应用正确的布局,避免初始状态异常。
内容的提问来源于stack exchange,提问作者Abhishek Srinivasan
相关产品推荐
相关产品推荐

