jQuery实现导航二级列hover显示及分类匹配问题求助
问题解决:导航hover时二级列反复闪烁的修复
问题根源
你遇到的反复显示隐藏问题,核心原因有两个:
- 遍历二级项时,每碰到一个不匹配的项就执行
menuLevelThree.hide(),导致三级菜单在遍历过程中被反复切换显示/隐藏状态 - 未处理鼠标离开后的隐藏逻辑,且没有清理动画队列,多次触发后造成动画堆积,引发闪烁
修复后的代码
$(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
相关产品推荐
相关产品推荐

