Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - change underline of active nav by section

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...