2016-07-16 56 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

请指定完整的HTML代码,因为代码中缺少少量元素,如menu_open, –

回答

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; 
    } 
    } 
}); 

});

});