簡體   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