2016-02-11 102 views
3

我正在使用jquery来突出显示我的导航栏时,它通过我的页面上的某些点,但有一部分导航没有被突出显示,直到它通过对象下面。具体的罪犯是该页面的联系人部分。scrollTop()返回元素下的位置

这里是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'); 
    } 
}); 

回答

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

+0

谢谢!我忽略了那一点,现​​在它正在工作! – Davez01d

+0

您好,欢迎光临! ;) – drosam

3

进行此茶NGE解决这个问题对我来说,我想你忘记了,你是治疗scrollTop为scrollTop的+导航栏高度

var scrollTop = $(window).scrollTop() + navHeight; 
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... 
}