单击下拉菜单中包含子菜单的列表项,关闭其余项但不扩展新项

时间:2013-07-09 13:43:25

标签: javascript jquery drop-down-menu toggle submenu

我正在创建一个下拉切换菜单,但我有一个问题,我无法绕过它。单击列表项会展开它的子项,但是当展开列表时,如果单击另一个列表,则第一个按照合同进行收缩,但第二个不会展开直到再次单击。我该如何解决这个问题?

单击列表时,会将一个类toggled添加到其顶级父容器中,以便我可以使用jQuery创建条件 - 这是代码:

$('#main-navigation a').click(function (e) {

/* Finding the drop down list that corresponds to the current section: */
var $dropdownMenu = $(this).next();

if ($dropdownMenu.hasClass('sub-menu')) { /* Checking if drop down menu exists for this menu item */
    if ($('.nav-menu > li').hasClass('toggled')) { /* There is toggled menu */
        if (($(this).parents().hasClass('toggled')) && (!$(this).parent().hasClass('toggled'))) {
            // The curent element has only a not-direct parent with "toggled" e.g. the element is deep link!');
            $dropdownMenu.slideToggle('fast');
        } else {
            //If the element is a top link, the class is removed and the lists dissappear
            $('li.toggled').removeClass('toggled').children('ul').slideUp('fast');
        }

    } else {
        // If there isn't a toggled menu, the current menu expands and a class is added
        $dropdownMenu.slideToggle('fast').parent('.nav-menu > li').addClass('toggled');
    }

}
})

整个HTML,CSS和JS代码在这里:http://jsfiddle.net/nUrjy/

我甚至不确定这是否是像这样的菜单的最佳方式..

1 个答案:

答案 0 :(得分:1)

在这里做了一点改变:http://jsfiddle.net/JWMarchant/nUrjy/7/

将代码简化为:

$('#main-navigation a').click(function (e) {
   /* Finding the drop down list that corresponds to the current section: */
   var dropdownMenu = $(this).next();

   if ($(this).parent('li').children('.sub-menu').length > 0) {
      $('.sub-menu').not(dropdownMenu).not(dropdownMenu.parents()).slideUp('fast');
      $(dropdownMenu).slideToggle('fast');
   }
});