You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

handleOrientationChange函数问题:设备横竖屏切换时Logo未切换

修复横竖屏切换时Logo不切换的问题

问题分析

当前代码无法响应横竖屏切换的核心原因:

  • 未定义isMobile变量,导致移动端的Logo切换逻辑完全不执行
  • isPortrait未使用let/const声明,会污染全局作用域
  • 仅依赖orientationchange和screen.orientation.change事件,部分场景(如桌面端窗口缩放模拟横竖屏、部分设备兼容性问题)无法覆盖

修复方案

  1. 补充isMobile的判断逻辑,通过UA或视口宽度检测移动端
  2. 声明局部变量避免全局污染
  3. 添加resize事件监听,覆盖更多屏幕尺寸变化场景
  4. 优化方向判断逻辑,直接在条件中使用媒体查询结果,减少变量冗余

修复后的代码

// 处理屏幕方向变化逻辑
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 14:58:19