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

jQuery实现导航二级列hover显示及分类匹配问题求助

问题解决:导航hover时二级列反复闪烁的修复

问题根源

你遇到的反复显示隐藏问题,核心原因有两个:

  1. 遍历二级项时,每碰到一个不匹配的项就执行menuLevelThree.hide(),导致三级菜单在遍历过程中被反复切换显示/隐藏状态
  2. 未处理鼠标离开后的隐藏逻辑,且没有清理动画队列,多次触发后造成动画堆积,引发闪烁

修复后的代码

$(function() {
  const itemLevelOne = $('.cs-navigation__item--level_1');
  const itemLevelTwo = $('.cs-navigation__item--level_2');
  const menuLevelThree = $('.cs-navigation__column___third');

  // 初始状态隐藏二级项和三级菜单
  itemLevelTwo.hide();
  menuLevelThree.hide();

  itemLevelOne.mouseenter(function() {
    const currentCatId = $(this).data('category-id');
    if (currentCatId) {
      // 先清除动画队列,批量隐藏所有二级项
      itemLevelTwo.stop(true, true).hide(200);
      // 筛选并显示匹配的二级项
      itemLevelTwo.filter(`[data-parent-category-id="${currentCatId}"]`).stop(true, true).show(200);
      // 显示三级菜单容器
      menuLevelThree.stop(true, true).show(200);
    }
  });

  // 鼠标离开整个导航容器时,隐藏二级项和三级菜单
  $('.cs-navigation').mouseleave(function() {
    itemLevelTwo.stop(true, true).hide(200);
    menuLevelThree.stop(true, true).hide(200);
  });
});

关键优化说明

  • 统一操作逻辑:先批量隐藏所有二级项,再筛选匹配项显示,避免遍历过程中反复切换三级菜单状态
  • 清理动画队列:用stop(true, true)清除未完成的动画,强制完成当前动画后执行新操作,彻底解决闪烁
  • 高效获取属性:用data()替代attr()获取data属性,性能更好且自动处理类型转换
  • 完善交互逻辑:给导航容器添加mouseleave事件,确保鼠标离开整个导航区域时自动隐藏二级列和菜单
  • 简化筛选逻辑:用filter()替代each()遍历,代码更简洁高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:50:45