繁体   English   中英

单击其他菜单时,jQuery隐藏子菜单

[英]jQuery hide submenu when other menu is clicked

我正在使用这个小脚本来创建带有子链接的水平菜单。 我已完成所有工作,但是有一个小障碍,那就是单击另一个子菜单时需要关闭该子菜单。 您可以在此处看到我的菜单,因此,如果您单击菜单一,然后单击菜单二,则菜单一子链接将消失。

这是菜单的jQuery:

$(function() {

// Dropdown toggle
$('.dropdown-toggle').click(function(){
  $(this).next('.dropdown').toggle();
});

$(document).click(function(e) {
  var target = e.target;
  if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
    $('.dropdown').hide();
  }
});

});

您可以设置每次单击将从所有.drop-down-items中删除Class .active,然后将active class添加到所单击的项目中,然后再添加.dropdown-toggle:not('。active')。hide()

您需要添加:

$('.dropdown').css('display', 'none');

因此,在打开下一个子菜单之前,它将关闭所有当前打开的菜单。 码:

// Dropdown toggle
$('.dropdown-toggle').click(function(){
  $('.dropdown').css('display', 'none'); //New code
  $(this).next('.dropdown').toggle();
});

在您的custom.js中,您可以更改以下行:

 // On click sub menu
 $('.dropdown-toggle').click(function(){
     $(this).next('.dropdown').toggle();
 });

 $(document).click(function(e) {
     var target = e.target;
     if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
         $('.dropdown').hide();
     }
 });

有:

//
// delegate the click event handler
//
$(document).on('click', '.dropdown-toggle', function(e) {
    //
    // is current submenu visible?
    //
    var  isVisible = $(this).next('.dropdown').is(':visible');
    //
    // hide all submenu, not current
    //
    $(this).siblings('.dropdown-toggle').next('.dropdown').hide();
    //
    // toggle the visibility of current menu: visible <--> invisible
    //
    $(this).next('.dropdown').toggle(!isVisible);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM