jQuery fadeOut()失效:点击关闭全屏子导航后元素立即复现如何解决
问题修复方案
问题根源
你的推测完全正确:关闭按钮位于li.menu-item-has-children元素内部,点击关闭按钮后鼠标仍停留在该父元素上,hover的触发逻辑会再次执行,导致子导航刚完成淡出就立即触发淡入。
修复思路
通过新增手动关闭的状态标记覆盖原有hover逻辑:
- 点击关闭按钮时给当前父导航项添加手动关闭的类标识
- hover触发子导航打开前,先判断当前导航项是否有手动关闭标记,有则不执行打开逻辑
- 鼠标移出父导航项时清除手动关闭标记,不影响下次hover触发打开效果
完整修改后的JS代码
$('li.menu-item-has-children').hover(function () { // 仅非手动关闭状态下触发子导航打开 if (!$(this).hasClass('manual-closed')) { // 加stop清除动画队列,避免多次触发导致的动画异常 $('ul.dropdown-menu-main', this).stop(true, true).fadeIn('slow'); $(this).parent().children().not(this).find('ul.dropdown-menu-main').stop(true, true).fadeOut(); // 打开当前菜单时清除其他菜单的手动关闭标记 $(this).parent().children().not(this).removeClass('manual-closed'); } }).on('mouseleave', function() { // 鼠标移出父元素后清除手动关闭标记,恢复正常hover逻辑 $(this).removeClass('manual-closed'); }); $('.close').click(function () { const $parentNav = $(this).closest('li.menu-item-has-children'); // 标记当前导航为手动关闭状态 $parentNav.addClass('manual-closed'); $('ul.dropdown-menu-main').stop(true, true).fadeOut('fast'); });
补充说明
原有CSS和HTML代码无需改动,修改后即可实现需求:hover打开子导航、移出不自动关闭、点击关闭按钮可正常关闭且不会立即回弹,下次hover该导航项仍可正常打开子导航。
内容的提问来源于stack exchange,提问作者Erwin van Ekeren
相关产品推荐
相关产品推荐

