按部分更改活动导航的下划线 [英] change underline of active nav by section

查看:69
本文介绍了按部分更改活动导航的下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个问题,但是第一个解决了.首先是在给定的div(或div的高度)之后使导航栏变粘.无论如何,我现在遇到的问题是,在活动部分上时,如何使导航链接带有下划线或更改颜色.例如,如果我在第一部分,则导航栏上的第一个链接带有下划线,当我向下滚动时,相应的链接和部分也会发生相同的情况.

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>

推荐答案

我想我了解您要执行的操作,最近我遇到了同样的问题.

I think I understand what you are looking to do, I had the same problem just recently.

您需要将每个部分的$(document).scrollTop()$(section).offset().top进行比较.取得活动部分的ID后,找到具有相同href的<a>进行突出显示.

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

});

您可以查看我的小提琴

这篇关于按部分更改活动导航的下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆