读取 DOM(网页)中的位置并相应地更改导航菜单 类

Read location in DOM (webpage) and change navmenu classes accordingly

我有一个链接到页面特定部分的导航菜单。我想写一些 JS,以便在滚动条经过 HTML 的相应部分时将 class 添加到每个导航菜单项。我相信我已经知道如何将 classes 添加到我的导航菜单项中,那么 JS 中是否有特定的方法来识别用户在 DOM 中的位置?

要动态更改导航栏中的 classes,我使用类似的东西:

jQuery(document).ready(function ($) {

        var menu_items_links = $(".menu li a");
        menu_items_links.each(function () {
            if ($(this).is('[href*="#CURRENT LOCATION IN DOM"]')) {
                $(this).parent().addClass('current-location');
            }
        })
    });

其中 class 会将 highlight/underline 添加到导航菜单项以表明用户位于特定位置。

您可以为此使用任何 scroll spy 插件或使用以下实现

$(window).bind('scroll', function() {
    var currentTop = $(window).scrollTop();
    var elems = $('.scrollspy');
    elems.each(function(index){
      var elemTop   = $(this).offset().top;
      var elemBottom    = elemTop + $(this).height();
      if(currentTop >= elemTop && currentTop <= elemBottom){ //Current location tracking
        var id      = $(this).attr('id');
        var navElem = $('a[href="#' + id+ '"]');
    navElem.parent().addClass('active').siblings().removeClass( 'active' );
      }
    })
}); 
.active{
  color: red;
  background-color: red;
}

#nav{
  position:fixed;
  top:0;
  right:50%;
}

section{
  min-height: 500px;
}
<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
   </head>
   <body>
      <nav id="nav" class="navbar navbar-template">
        <div class="row col-xs-12 text-center">
          <ul>
            <li class="active">
              <a href="#Home">Home</a>
            </li>
            <li>
              <a href="#AboutUs">AboutUs</a>
            </li>
            <li>
              <a href="#Images">Images</a>
            </li>
            <li>
              <a href="#Contact">Contact</a>
            </li>
          </ul>
        </div>
      </nav>

      <section class="scrollspy" id="Home">
      Home
      </section>

      <section class="scrollspy" id="AboutUs">
      AboutUs
      </section>

      <section class="scrollspy" id="Images">
      Images
      </section>

      <section class="scrollspy" id="Contact">
      Contact
      </section>
</body>

看看这个滚动间谍插件https://github.com/r3plica/Scrollspy

所以最终对我有用的是使用 WaypointJS。我基本上只是在 DOM 的特定部分设置 waypoints,然后我可以定义我想要在这些地方发生的事情。这是最后的代码:

jQuery(document).ready(function ($) {

    var menu_items_links = $(".menu li a");
    menu_items_links.each(function () {
        if ($(this).is('[href*="#"]')) {
            $(this).parent().removeClass('current-menu-item current-menu-ancestor');
        }
    })
    
    new Waypoint({
      element: document.getElementById('explore'),
      direction: 'down',
      handler: function() {
        console.log("FIRST WAYPOINT IS ACTIVE.");
        document.querySelector("a[href='/manitoba/#explore']").parentElement.classList.add('current-menu-item', 'current-menu-ancestor');
        document.querySelector("a[href='/manitoba/#build']").parentElement.classList.remove('current-menu-item', 'current-menu-ancestor');
        document.querySelector("a[href='/manitoba/#connect']").parentElement.classList.remove('current-menu-item', 'current-menu-ancestor');
      },
      offset: '25%',
      continuous: false
  });  

  new Waypoint({
    element: document.getElementById('explore'),
    direction: 'up',
    handler: function() {
      console.log("DEACTIVATING WAYPOINT.");
      document.querySelector("a[href='/manitoba/#explore']").parentElement.classList.remove('current-menu-item', 'current-menu-ancestor');
    },
    offset: '35%',
});  

  new Waypoint({
    element: document.getElementById('build'),
    handler: function() {
      console.log("SECOND WAYPOINT IS ACTIVE.");
      document.querySelector("a[href='/manitoba/#build']").parentElement.classList.add('current-menu-item', 'current-menu-ancestor');
      document.querySelector("a[href='/manitoba/#explore']").parentElement.classList.remove('current-menu-item', 'current-menu-ancestor');
      document.querySelector("a[href='/manitoba/#connect']").parentElement.classList.remove('current-menu-item', 'current-menu-ancestor');
    },
    offset: '50%',
    continuous: false
}); 

new Waypoint({
    element: document.getElementById('connect'),
    handler: function() {
      console.log("THIRD WAYPOINT IS ACTIVE.");
      document.querySelector("a[href='/manitoba/#connect']").parentElement.classList.add('current-menu-item', 'current-menu-ancestor');
      document.querySelector("a[href='/manitoba/#build']").parentElement.classList.remove('current-menu-item', 'current-menu-ancestor');
      document.querySelector("a[href='/manitoba/#explore']").parentElement.classList.remove('current-menu-item', 'current-menu-ancestor');
    },
    offset: '50%',
    continuous: false
    });  
});