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

窗口 resize 时用 jQuery 移动菜单元素:右移正常左移失效问题

解决响应式窗口调整时元素双向移动的问题

看起来你现在遇到的问题是只能把导航元素从左侧移到右侧,但没办法在窗口变大的时候移回去对吧?这大概率是因为你只处理了「缩小窗口」的单向逻辑,没考虑反向的情况,而且可能没保存元素原本的位置信息,导致移回来的时候找不到正确的放置点。我来给你梳理一下完整的解决方案:

首先先补全你的HTML结构(推测你可能漏写了右侧的目标容器,先加上以便测试):

<div class="container">
  <div class="row">
    <div class="col-10" id="left_bar">
      <ul class="nav" id="target_nav"> <!-- 给导航加个ID方便精准定位 -->
        <li class="nav-item">
          <a class="nav-link" href="#">All (181)</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Spec...</a>
        </li>
      </ul>
    </div>
    <!-- 新增右侧目标容器 -->
    <div class="col-2" id="right_bar"></div>
  </div>
</div>

接下来是核心的JavaScript逻辑,重点解决双向移动和性能优化的问题:

// 获取关键元素与容器
const targetNav = document.getElementById('target_nav');
const leftBar = document.getElementById('left_bar');
const rightBar = document.getElementById('right_bar');
// 保存导航的原始父容器,用于判断当前位置
const originalParent = leftBar;
// 设置响应式断点(这里用Bootstrap的md断点768px,可根据需求调整)
const breakpoint = 768;

// 防抖函数:避免窗口resize时频繁触发逻辑,提升性能
function debounce(func, wait) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(func, wait);
  };
}

// 处理元素移动的核心逻辑
function handleNavMove() {
  const windowWidth = window.innerWidth;
  
  // 窗口宽度小于断点,且导航不在右侧容器时,移到右侧
  if (windowWidth < breakpoint && targetNav.parentElement !== rightBar) {
    rightBar.appendChild(targetNav);
  } 
  // 窗口宽度大于等于断点,且导航不在原始左侧容器时,移回左侧
  else if (windowWidth >= breakpoint && targetNav.parentElement !== originalParent) {
    originalParent.appendChild(targetNav);
  }
}

// 页面加载时先执行一次,确保初始状态正确
window.addEventListener('load', handleNavMove);
// 监听窗口resize事件,用防抖优化执行频率
window.addEventListener('resize', debounce(handleNavMove, 200));

关键逻辑说明:

  • 保存原始父容器:这是实现双向移动的核心,我们需要明确元素原本属于哪个容器,才能在窗口恢复大小时准确移回原位
  • 判断当前位置:每次执行移动前先检查元素当前的父容器,避免重复执行append操作(虽然不会报错,但会浪费性能)
  • 防抖函数:窗口resize事件会高频触发,防抖能让逻辑在窗口调整停止后再执行,减少不必要的计算

如果你习惯用jQuery,也可以用类似逻辑实现:

const $targetNav = $('#target_nav');
const $leftBar = $('#left_bar');
const $rightBar = $('#right_bar');
const breakpoint = 768;

function handleNavMove() {
  const windowWidth = $(window).width();
  if (windowWidth < breakpoint && $targetNav.parent().attr('id') !== 'right_bar') {
    $targetNav.appendTo($rightBar);
  } else if (windowWidth >= breakpoint && $targetNav.parent().attr('id') !== 'left_bar') {
    $targetNav.appendTo($leftBar);
  }
}

$(window).on('load resize', debounce(handleNavMove, 200));

// jQuery版防抖函数
function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:25:45