固定菜单与achors到错误的位置

时间:2016-02-09 23:32:49

标签: javascript jquery html css

我的页面下有一个锚点菜单。当您单击任何一个链接时,它会向下滚动到右侧部分,但如果您单击同一链接,则会更改其位置(减去57px)。如何在页面加载后从头开始获得正确的位置?

这是我的代码:

$(document).ready(function(){
var top = $('#anchor-menu').offset().top;
$(window).scroll(function(){
    var y = $(this).scrollTop();
    if (y >= top) {
        $('#anchor-menu').addClass('fixed');
    }
    else {
        $('#anchor-menu').removeClass('fixed');
    }
});
$('#menu-anchor-menu li').each(function(){
    var hash = $(this).find('a').attr('href');
    var tag = hash.split('#');
    $(this).find('a').click(function(e){
        e.preventDefault();
        var pos = $('#'+tag[1]).offset().top - $('#anchor-menu').height();
        $('html, body').stop().animate({
            scrollTop: pos
        }, 1500, 'easeInOutExpo');
        $('#menu-anchor-menu li a').removeClass('active');
        $(this).addClass('active');
        return false;
    });
});
});

1 个答案:

答案 0 :(得分:0)

所以发生的事情是:

  1. 点击事件发生时,您在应用固定类之前抓住高度,因此您错误地计算了高度。
  2. 您的动画代码滚动会触发
  3. 您的滚动事件会触发并添加固定类
  4. 滚动到错误的顶部。
  5. 修复是在发生点击事件时“检查”滚动事件中的逻辑,或者是阻止上述步骤发生的其他一些神奇方法。解决方案如下,我不知道它是否是最好的。

    $(document)
      .ready(documentReady);
    
    function checkScroll() {
      var $menu = $('#anchor-menu');
      var top = $menu.offset().top,
                y = $menu.scrollTop();
      if (y >= top) {
        $menu.addClass('fixed');
      } else {
        $menu.removeClass('fixed');
      }
    }
    
    function documentReady() {
      $(window)
        .scroll(checkScroll);
    
      $('#menu-anchor-menu li')
         .each(forEachLi);
    
      function forEachLi() {
        checkScroll();
    
        var hash = $(this).find('a').attr('href');
        var tag = hash.split('#');
        $(this).find('a').click(anchorClicked);
    
        function anchorClicked(e) {
          e.preventDefault();
          var pos = $('#' + tag[1]).offset().top - $('#anchor-menu').height();
          $('html, body').stop().animate({
            scrollTop: pos
          }, 1500, 'easeInOutExpo');
          $('#menu-anchor-menu li a').removeClass('active');
          $(this).addClass('active');
          return false;
        }
      }
    }