Home>

There may be such a requirement in common development pages,There will be multiple modules in the page,Each module corresponds to a navigation,When the page scrolls to a module,The corresponding module navigation needs to add a class to distinguish the area browsed by the current user.

Assume the structure is as follows:

<div>
  <div>
    <div>section1</div>
    <div>section2</div>
    <div>section3</div>
    <div>section4</div>
    <div>section5</div>
  </div>
  <nav>
    <a href="#section1" rel="external nofollow">section1</a>
    <a href="#section2" rel="external nofollow">section2</a>
    <a href="#section3" rel="external nofollow">section3</a>
    <a href="#section4" rel="external nofollow">section4</a>
    <a href="#section5" rel="external nofollow">section5</a>
  </nav>
</div>

Navigation and positioning while the page is scrolling

The js code is as follows:

var $navs=$("nav a"), //navigation
  $sections=$(". section"), //module
  $window=$(window),  navlength=$navs.length-1;
$window.on ("scroll", function () {
  var scrolltop=$window.scrolltop (),    len=navlength;
  for (;len>-1;len--) {
    var that=$sections.eq (len);
    if (scrolltop>= that.offset (). top) {
       $navs.removeclass ("current"). eq (len) .addclass ("current");
       break;
    }
  }
});

The effect is as follows:

not difficult to see,The basic principle is that when the window is scrolled,Traverse the modules from back to front,If the window's scroll height is greater than or equal to the distance of the current module from the top of the page,Highlight the navigation corresponding to the current module,And no longer traversing

Click to navigate to the page

In addition to this demand,There is another need,That is, click to navigate to the top of the module corresponding to the navigation.

code show as below:

$navs.on ("click", function (e) {
  e.preventdefault ();
  $("html, body"). animate ({
    "scrolltop":$($(this) .attr ("href")). offset (). top
  }, 400);
});

The effect is as follows:

  • Previous Java IO Stream Common API Examples of File Class
  • Next JavaScript game