【问题标题】:jQuery hide submenu when other menu is clicked单击其他菜单时jQuery隐藏子菜单
【发布时间】:2017-06-30 12:29:33
【问题描述】:

我正在使用this 小脚本创建带有子链接的水平菜单。我一切正常,但有一个小障碍,那就是我需要在单击另一个子菜单时关闭子菜单。你可以看到我的菜单here我需要它,这样如果你点击菜单一,然后点击菜单二,那么菜单一的子链接就会消失。

这里是菜单的 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();
  }
});

});

【问题讨论】:

  • Jsfiddle 的例子真的很有帮助。

标签: javascript jquery menu


【解决方案1】:

你需要添加:

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

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

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

【讨论】:

  • 完美。谢谢你
【解决方案2】:

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

【讨论】:

  • 如果有一些 jsfiddle sn-p 我可以让它更简单,但我希望你明白我的想法:)
【解决方案3】:

在您的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);
});

【讨论】:

    猜你喜欢
    • 2019-09-19
    • 1970-01-01
    • 2012-12-13
    • 2013-04-19
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 2018-10-13
    • 2013-06-20
    相关资源
    最近更新 更多