无法让Mega Menu(巨型菜单)的两种交互行为同时正常工作
巨型菜单交互冲突:点击自身无法重置图标旋转角度
我开发的巨型菜单有两种交互需求,单独实现都正常,但合并后点击已激活的菜单自身时,菜单能收起(移除.show类),但图标无法旋转回0度:
- 行为1:点击菜单链接时,展开自身子菜单并旋转图标;点击其他兄弟菜单时,收起当前激活菜单并重置其图标角度
- 行为2:再次点击已激活的菜单链接时,收起自身子菜单并重置图标角度
原代码如下:
window.addEventListener("load", function () { $('li.mega-menu-link').on('click', function (e) { var menuItem = $(e.currentTarget); menuItem.parent().children('li.mega-menu-link').attr('aria-expanded', 'false'); menuItem.attr('aria-expanded', 'true'); menuItem.parent().children().children('.megamenu-item').removeClass('show'); if ($('.megamenu-item').hasClass('show')){ menuItem.parent().children().children().children('.sgds-icon').css('transform', 'rotate(180deg)'); menuItem.children().children('.sgds-icon').css('transform', 'rotate(0deg)'); } { menuItem.parent().children().children().children('.sgds-icon').css('transform', 'rotate(0deg)'); menuItem.children().children('.sgds-icon').css('transform', 'rotate(180deg)'); } }); });
问题分析
- 条件判断错误:用
$('.megamenu-item').hasClass('show')检查全局所有子菜单,而非当前点击项的子元素,逻辑完全偏离需求 - 语法错误:if块后直接写
{,缺少else关键字,导致第二个代码块永远执行 - 逻辑顺序颠倒:先全局移除了所有
.show类,再判断状态,导致条件永远为假 - 选择器范围过大:操作图标时用了多层子元素选择器,会误操作所有兄弟项的图标
修复后的代码
window.addEventListener("load", function () { $('li.mega-menu-link').on('click', function (e) { e.preventDefault(); const $menuItem = $(this); const $currentMegaItem = $menuItem.children('.megamenu-item'); const isExpanded = $currentMegaItem.hasClass('show'); // 重置所有兄弟项的状态 $menuItem.siblings('.mega-menu-link') .attr('aria-expanded', 'false') .children('.megamenu-item') .removeClass('show') .find('.sgds-icon') .css('transform', 'rotate(0deg)'); if (isExpanded) { // 当前菜单已展开,执行收起逻辑 $menuItem.attr('aria-expanded', 'false'); $currentMegaItem.removeClass('show'); $currentMegaItem.find('.sgds-icon').css('transform', 'rotate(0deg)'); } else { // 当前菜单未展开,执行展开逻辑 $menuItem.attr('aria-expanded', 'true'); $currentMegaItem.addClass('show'); $currentMegaItem.find('.sgds-icon').css('transform', 'rotate(180deg)'); } }); });
关键改动说明
- 先判断当前点击项的子菜单状态(
isExpanded),确保逻辑基于当前项的实际情况 - 用
siblings()精准定位兄弟菜单,避免全局选择器的副作用 - 拆分逻辑:先重置所有兄弟项,再单独处理当前项的展开/收起
- 修正语法错误,明确if/else分支的执行逻辑
- 添加
e.preventDefault()防止菜单链接默认跳转(如果是a标签的话)
内容的提问来源于stack exchange,提问作者potatowaffle
相关产品推荐
相关产品推荐

