簡體   English   中英

當打開另一個菜單項時,MegaMenu不會關閉子菜單

[英]MegaMenu doesn't close submenu when open another menu item

我的MegaMenu有點問題,當我打開一個子菜單(單擊主菜單中的一項)時,我希望該子菜單在我單擊文檔正文中的任何位置時消失,或者如果我選擇其他菜單項,則前一個子菜單具有關閉,如果我單擊該子菜單('ul')或該子菜單上的一個特定項目,它的工作方式就像我想要的(它關閉),但是如果我單擊其他菜單項,則上一個子菜單保持打開狀態,從而創建了子菜單層我必須單擊以使其消失(或單擊使它們顯示的主菜單項),但我不確定我是否清楚,該函數JS im使用:

$(".menu > ul > li").click(function(e) {
              if ($(window).width() > 943) {
                  $(this).children('ul').fadeToggle(15);
                  $(this).children('ul').toggleClass('center');
                  e.preventDefault();
              }
          });

因此,我的代碼有些復雜:

https://codepen.io/anon/pen/JpBrRp

休息,我相信我了解這個問題。

首先,您必須檢查要打開的元素是否已經打開。 如果打開,則將關閉;否則,將關閉。

      $(".menu > ul > li").click(function(e) {
          if ($(window).width() > 943) { 
            if ($(this).children('.menu-list').is(":visible")){
               $(this).children('.menu-list').fadeToggle(15);
               $(this).children('.menu-list').toggleClass('center');
              e.preventDefault();
            } else {
               $('.menu-list').hide();
               $('.menu-list').removeClass('center');
               $(this).children('.menu-list').fadeToggle(15);
               $(this).children('.menu-list').toggleClass('center');
              e.preventDefault();
            }
          }
      });

然后,您需要另一個功能來驗證用戶是否在非菜單的其他位置單擊以關閉子菜單。

     $("body").click(function(e) {
         var target = e.target;
        if (target.className.indexOf("menu-button") == -1 && target.offsetParent.className.indexOf("menu-button") == -1 ) {
              $('.menu-list').hide();
              $('.menu-list').removeClass('center');
            return;
        }
      });

看看這是否對您有幫助: https : //codepen.io/beduardo/pen/zReyjj

提示:我建議避免使用,只能使用標簽來引用js中的元素。 將來這可能是個問題。

謝謝我的朋友布魯諾·愛德華多,我相信你會葡萄牙語! Obrigado朋友!! 只有一個小錯誤,僅當您單擊按鈕時它才起作用,如果您單擊圖像則它不起作用,以解決需要將菜單按鈕添加到鏈接內的每個標記的問題。 例如:

<a role="button" class="button button4 **menu-button**"><i class="icon-crm fs1 icon **menu-button**"></i><span class="button-text rowcenter **menu-button**">{{'MenuItem1' | translate}}</span></a>

謝謝你,朋友!

是的,我了解葡萄牙語=)。 這種方法很好,另一種方法是改進功能,以驗證用戶是否在其他地方單擊。

if (target.className.indexOf("menu-button") == -1 && target.offsetParent.className.indexOf("menu-button") == -1 )

隨意選擇更好的給您=)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM