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

如何在屏幕宽度超过指定值时自动恢复头部位置及相关事件?

解决响应式菜单的屏幕尺寸适配问题

核心思路

通过监听窗口尺寸变化,结合状态变量控制header的位置和菜单点击事件的有效性,确保大屏幕下自动恢复初始状态。

具体实现步骤

  1. 定义基础变量与初始状态
    获取目标元素,初始化状态变量标记当前是否为移动端、是否已偏移:

    const header = document.querySelector('header');
    const menuIcon = document.querySelector('.menu-icon');
    let isShifted = false;
    let isMobile = window.innerWidth < 987;
    
  2. 编写菜单点击逻辑
    点击事件中先判断当前是否为移动端,再执行偏移切换:

    function toggleHeaderShift() {
      if (!isMobile) return;
      isShifted = !isShifted;
      header.style.transform = isShifted ? 'translateX(150px)' : 'translateX(-150px)';
    }
    
  3. 监听窗口尺寸变化,自动重置状态
    当屏幕宽度超过789px时,强制恢复header初始位置,移除或禁用点击事件;回到移动端范围时重新绑定事件:

    function handleResize() {
      const currentWidth = window.innerWidth;
      if (currentWidth > 789) {
        // 大屏幕下重置状态
        isShifted = false;
        header.style.transform = 'translateX(0)';
        menuIcon.removeEventListener('click', toggleHeaderShift);
        isMobile = false;
      } else if (currentWidth < 987 && !isMobile) {
        // 回到移动端,重新绑定事件
        menuIcon.addEventListener('click', toggleHeaderShift);
        isMobile = true;
      }
    }
    
  4. 初始化事件绑定
    页面加载时根据当前屏幕尺寸绑定对应事件:

    if (isMobile) {
      menuIcon.addEventListener('click', toggleHeaderShift);
    }
    window.addEventListener('resize', handleResize);
    

优化建议

  • CSS兜底:添加媒体查询,确保大屏幕下header样式强制重置,避免JS未及时触发的情况:
    @media (min-width: 790px) {
      header {
        transform: translateX(0) !important;
      }
    }
    
  • 防抖处理:给resize事件添加防抖,减少频繁触发的性能消耗:
    function debounce(func, delay = 100) {
      let timeoutId;
      return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
      };
    }
    window.addEventListener('resize', debounce(handleResize));
    

内容的提问来源于stack exchange,提问作者Ahid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:05:52