2016-07-16 8 views
0

クラスをボディに追加することで、「メニュー」を閉じるアンカーリンクを取得しようとしています。アンカーされたリンクのスクロールがメニューのクローズ機能を妨害する

問題は、メニューにナビゲーションの一部としてリンクが固定されていることです。クラスをチェックし、アンカーされたリンクに行く前にtoggleClassを実行する関数を追加しようとしています。

<script type="text/javascript"> 
$(document).ready(function(e) { 

// Working JS that Identifies the Class and Adds the "menu_open" or toggles to Subtract 
$(".menu, .arrow1, .menuAccountAccess").on("click", function() { 
    $(this).toggleClass("active"); 
    $('body').toggleClass('menu_open'); 
}); 

// The Main Navigation has some anchored links and the below code does not work as we also have a # link scroll code 
$(".NavigationAnchoredLinkClass").on("click", function() { 
    $('body').toggleClass('menu_open'); 
}); 

// Scroll function for Anchored Links 
$(function() { 
    $('a[href*="#"]:not([href="#"])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
      if (target.length) { 
       $('html, body').animate({ 
        scrollTop: target.offset().top - 60 
      }, 1000); 
     return false; 
     } 
    } 
    }); 
}); 

}); 
</script> 

<body class=""> 
     <p> 
     Anchored Links work fine with a <a href="#anchoredlink">Link</a> 
     </p> 
     <ul> 
     <li class="NavigationAnchoredLinkClass"> 
      <a href="siteurl/#achoredlink">Link</a> 
     </li> 
     </ul> 
</body> 
+0

あなたはmenu_openのようなコードに欠けている要素がほとんどないので、HTMLコードを完成させてください。 –

答えて

0

アンカーリンクスクロールにチェッククラスを追加しました。すべてのチェッククラスはbody divに "menu_open"があるかどうかを確認します。 "menu_open"が見つかると、クラスを空白に切り替え、別の関数が実行されるときにメニューを閉じます。

<script type="text/javascript"> 
$(document).ready(function(e) { 
    $(function() { 
    $('a[href*="#"]:not([href="#"])').click(function() { 

    // checks body for class 
    if ($('body').hasClass('menu_open')) { 
     // if class is found it toggles the class to blank which closes the menu 
     $('body').toggleClass('menu_open'); 
    } 

    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
    var target = $(this.hash); 
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
    if (target.length) { 
     $('html, body').animate({ 
     scrollTop: target.offset().top - 60 

     }, 1000); 
     return false; 
    } 
    } 
}); 

});

});

関連する問題