handleOrientationChange函数问题:设备横竖屏切换时Logo未切换
修复横竖屏切换时Logo不切换的问题
问题分析
当前代码无法响应横竖屏切换的核心原因:
- 未定义
isMobile变量,导致移动端的Logo切换逻辑完全不执行 isPortrait未使用let/const声明,会污染全局作用域- 仅依赖
orientationchange和screen.orientation.change事件,部分场景(如桌面端窗口缩放模拟横竖屏、部分设备兼容性问题)无法覆盖
修复方案
- 补充
isMobile的判断逻辑,通过UA或视口宽度检测移动端 - 声明局部变量避免全局污染
- 添加
resize事件监听,覆盖更多屏幕尺寸变化场景 - 优化方向判断逻辑,直接在条件中使用媒体查询结果,减少变量冗余
修复后的代码
// 处理屏幕方向变化逻辑 function handleOrientationChange() { const logoImage = document.getElementById('logo'); // 判断是否为移动端(可根据需求调整判断规则) const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); const isPortrait = window.matchMedia("(orientation: portrait)").matches; if (isMobile) { logoImage.src = isPortrait ? '/images/logo_small.svg' : '/images/logo.svg'; } } // 监听多种屏幕变化事件 window.addEventListener("orientationchange", handleOrientationChange); window.addEventListener("resize", handleOrientationChange); screen.orientation?.addEventListener("change", handleOrientationChange); // 页面加载时初始化 document.addEventListener("DOMContentLoaded", handleOrientationChange);
页面结构保持不变:
<nav> <a href="/"> <img id="logo" alt="Logo" src="/images/logo.svg"> </a> <ul class="nav-menu" > <li> <a href="about.html">About</a> </li> </ul> </nav>
额外说明
- 移动端判断规则可根据实际需求调整,比如通过
window.innerWidth判断(如window.innerWidth < 768) - 使用可选链
screen.orientation?.addEventListener避免部分浏览器不支持screen.orientation时抛出错误
内容的提问来源于stack exchange,提问作者Dmitry Bubnenkov
相关产品推荐
相关产品推荐

