2016-03-27 5 views
1

ドロップダウンリストを含む簡単なナビゲーションメニューを作成しようとしています。私はlate-CSSの使用のためにjQueryを使って 'data-dropdown'属性を 'opened'または 'closed'に設定しました。私は、「Modernizr.touchevents」を使用して、ホバー/クリックの動作を決定します。ここに私のコードです:クリック時のjQueryドロップダウンメニュー(2回目のクリック時)親

(function ($) { 

    "use strict"; 

    var menu = $('.navbar .menu'); 

    // Return early if there's no menu 
    if (! menu) { 
     return; 
    } 

    var dropdownLi = menu.find('.menu-item-has-children'); 
    var dropdownLink = menu.find('.menu-item-has-children > a'); 

    // Return early if there's no dropdown 
    if (! dropdownLi) { 
     return; 
    } 

    // Set attr to all dropdowns by default 
    dropdownLi.attr('data-dropdown', 'closed'); 

    // Use modernizr to decide on touch/hover behaviour 
    if (Modernizr.touchevents) { 

     dropdownLink.click(function(event) { 

      // Set 'data-dropdown' attr to 'opened' 
      $(this).parent().attr('data-dropdown', 'opened'); 

      // Set 'data-dropdown' attr on other submeus to 'closed' 
      $(this).parent().siblings().attr('data-dropdown', 'closed'); 

      // Set 'data-dropdown' attr on other nested subenus to 'closed' 
      $(this).parent().siblings().find('.menu-item-has-children').attr('data-dropdown', 'closed'); 

      // Prevent default click 
      return false; 
      // event.preventDefault(); 
      // event.stopImmediatePropagation(); 

     }); 

     // Close all menus on scroll 
     $('.site-wrapper').scroll(function() { 
      dropdownLi.attr('data-dropdown', 'closed'); 
     }); 

     // Close all dropdowns when clicked anywhere 
     $(document).click(function() { 
      dropdownLi.attr('data-dropdown', 'closed'); 
     }); 

    } else { // Now hover behaviour 

     dropdownLi.each(function() { 

      $(this).mouseenter(function() { 
       $(this).attr('data-dropdown', 'opened'); 
      }); 

      $(this).mouseleave(function() { 
       $(this).attr('data-dropdown', 'closed'); 
      }); 

     }); 

     // Prevent default click if there's just a `#` instead of a link 
     dropdownLink.on('click', function(){ 
      if (this.href.indexOf('#') != -1) { 
       return false; 
       // event.preventDefault(); 
       // event.stopImmediatePropagation(); 
      } 
     }); 

    } 


})(jQuery); 

今問題です。 'dropdownLink'は有効なhref属性(#ではなく)を持つことができます。この場合、2回目のクリックで動作するように動作する必要があります。したがって、タッチデバイス上では、最初のクリックでドロップダウンが開き、2番目のページでGoogleにURLが送信されます。

答えて

2

あなたの問題を正しく理解している場合(HTMLなしでややこしい)、余分なチェックが必要です(あなたのHTMLがないので確認していません):

... 

dropdownLink.click(function(event) { 

    if($(this).parent().attr('data-dropdown') != 'opened') { 

      // Set 'data-dropdown' attr to 'opened' 
      $(this).parent().attr('data-dropdown', 'opened'); 

... 

ので、メニューが開かれていない場合、それはそれを行うとfalseを返します(これにより、URLに行く回避)し、リンクが扱われますクリックされている二度目...

を追加しましたフィドル:https://jsfiddle.net/fekadgjr/

+1

あなたの答えは正しいです!今私は自分自身でそれをどうやって取得しなかったのか、自分自身に疑問を抱いています。ありがとうございました! – Baltar

+1

時々あなたはそれをあまりにも長く見て、それから自分の考えに迷ってしまいます!お役に立てて嬉しいです :) –

関連する問題