2016-02-11 56 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... 
}