scrollTop()返回元素下面的位置

时间:2016-02-11 22:28:32

标签: javascript jquery css

我使用jquery突出显示我的导航栏,当它通过我的页面上的某些点时,但有一部分导航器没有被突出显示,直到它从对象下面经过。具体罪犯是该页面的联系部分。

这是codepen - http://codepen.io/Davez01d/pen/NxMzYy?editors=0010

这是相关的html -

<hr id="contact-anchor" class="line section-seperator">

css -

.on-section {
  background-color: #2766af !important;
  color: white;
}
.on-section:focus {
  color: white;
}

和javascript -

$(window).scroll(function() {
  var navHeight = $(".navbar").outerHeight();
  var scrollTop = $(window).scrollTop(); 
  var aboutPoint = $('#about').offset().top;
  var lineMargin = parseInt($('.section-seperator').css('marginTop'));
  var portfolioPoint = $('#portfolio-anchor').offset().top;
  var contactPoint = $('#contact-anchor').offset().top;

  if (scrollTop < aboutPoint)  {
    $('#home-btn').addClass('on-section');
    $('#about-btn').removeClass('on-section');
  } else if (scrollTop > aboutPoint && scrollTop < (portfolioPoint - navHeight)) {
    $('#home-btn').removeClass('on-section');
    $('#about-btn').addClass('on-section');
    $('#portfolio-btn').removeClass('on-section');
  } else if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint) {
    $('#about-btn').removeClass('on-section');
    $('#portfolio-btn').addClass('on-section');
    $('#contact-btn').removeClass('on-section');
  } else if (scrollTop > (contactPoint - navHeight)) {
    $('#portfolio-btn').removeClass('on-section');
    $('#contact-btn').addClass('on-section');
  }
});

3 个答案:

答案 0 :(得分:3)

进行此更改可以解决我的问题,我认为您忘记了将scrollTop视为scrollTop +导航栏高度

var scrollTop = $(window).scrollTop() + navHeight;

答案 1 :(得分:1)

要突出显示about,请执行此操作

if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint)

你必须退出.navbar身高(就像你在其他人身上做的那样)

if (scrollTop > (portfolioPoint - navHeight) && scrollTop < (contactPoint - navHeight))

在这里,您的codepen正常工作http://codepen.io/anon/pen/XXoLWM?editors=0110

答案 2 :(得分:1)

您的更新笔是here。切换按钮时计算出现问题或条件更好:

} else if (scrollTop > (portfolioPoint - navHeight) && scrollTop < contactPoint)) {
    // in this condition you stick too long, you forgot the navHeight
} else if (scrollTop > (contactPoint - navHeight)) {
    // therefore you reach this too late
}

在这里的第一个条件中你需要添加navheight:

} else if (scrollTop > (portfolioPoint - navHeight) && 
  scrollTop < (contactPoint - navHeight))) {
    // like this it works
} else if (scrollTop > (contactPoint - navHeight)) {
    // and here we go...
}