问题
So i had two problems but solved the first. The first was getting a nav bar to be sticky after a given div (or in this case the height of the div). Anyway the problem I have now is how can i get the nav links to be underlined or change color when on the active section. ie if I am on the first section the first link on the nav bar is underlined and when I scroll down the same happens for the respective links and sections.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(window).scroll(function () {
if ($(window).scrollTop() > 550) {
$('#nav_bar').addClass('navbar-fixed');
}
if ($(window).scrollTop() < 551) {
$('#nav_bar').removeClass('navbar-fixed');
}
});
});
</script>
<div id="page">
<!--top section-->
<section id="first">
<div class="top headline"><img src="" alt="Logo"></div>
<div class="top-with">with</div>
<div class="max-top"><img src="" alt="Logo"></div>
</section>
</div>
<!-- fixed nav-bar -->
<div id='nav_wrapper'>
<nav id='nav_bar'>
<ul id='nav_links'>
<img src="" alt="max-logo">
<li class="active">
<li><a href="#first">1</a></li>
<li><a href="#second">2</a></li>
<li><a href="#third">3</a></li>
<li><a href="#fourth">4</a></li>
<li><a href="#fifth">5</a></li>
</li>
</ul>
</nav>
</div>
回答1:
I think I understand what you are looking to do, I had the same problem just recently.
You need to compare the $(document).scrollTop()
with the $(section).offset().top
of each sections. Once you got the ID of the active section find the <a>
with the same href to apply some highlighting.
$(document).scroll(function(){
var st = $(this).scrollTop();
$(section).each(function() {
if(st > $(this).offset().top && st <= $(this).offset().top + $(this).height() ){
var id = $(this).attr('id');
$('a[href="#'+id+'"]').addClass('active');
}else{
var id = $(this).attr('id');
$('a[href="#'+id+'"]').removeClass('active');
}
});
});
You can check out my fiddle
来源:https://stackoverflow.com/questions/19697696/change-underline-of-active-nav-by-section