Smart positioning of Page scrolling and Javascript navigation using javascript
A common development page may have such a requirement. There are multiple modules on the page. Each module corresponds to a navigation module. When the page is rolled to a module, you need to add a class to the module navigation to differentiate the browsing area of the current user.
Assume that the structure is as follows:
<div class="container"> <div class="wrapper"> <div class="section" id="section1">section1</div> <div class="section" id="section2">section2</div> <div class="section" id="section3">section3</div> <div class="section" id="section4">section4</div> <div class="section" id="section5">section5</div> </div> <nav> <a href="#section1" rel="external nofollow" class="current">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 during Page 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:
It is not hard to see that the basic principle is to traverse the module from the back to the front when the window is rolling. If the rolling height of the window is greater than or equal to the distance from the current module to the top of the page, the corresponding navigation of the current module is highlighted, and the traversal is no longer performed.
Click the navigation page
In addition to this requirement, another requirement is to click the navigation bar to locate the top of the corresponding module in the navigation bar.
The Code is as follows:
$navs.on('click', function(e) { e.preventDefault(); $('html, body').animate({ 'scrollTop': $($(this).attr('href')).offset().top }, 400);});
The effect is as follows:
The above basically satisfies the basic business needs. This is the experience summarized in the work. I hope it will be helpful for everyone's learning, and I hope everyone can support the house of helping customers.