Home >Web Front-end >JS Tutorial >Javascript implementation of navigation anchor scrolling effect example
This article mainly introducesJavascriptimplementation of intelligent positioning when scrolling the pageNavigation, which has certain reference value. Interested friends can refer to it
Common development pages may have such a requirement. There will be multiple modules in the page, and each module corresponds to a navigation. When the page scrolls to a certain module, the corresponding module navigation needs to be added. A class used to distinguish the area that the current user is browsing.
Assume the structure is as follows:
<p class="container"> <p class="wrapper"> <p class="section" id="section1">section1</p> <p class="section" id="section2">section2</p> <p class="section" id="section3">section3</p> <p class="section" id="section4">section4</p> <p class="section" id="section5">section5</p> </p> <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> </p>
Navigation positioning when the page scrolls
jsThe code is as follows:
var $navs = $('nav a'), // 导航 $sections = $('.section'), // 模块 $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 difficult to see that the basic principle is to traverse the modules from back to front when the window is scrolling. If the scroll height of the window is greater than or equal to the distance of the current module from the top of the page, then the navigation corresponding to the current module will be highlighted and the traversal will no longer continue
Click the navigation to locate the page
In addition to this requirement, there is another requirement, which is to click on the navigation to locate the top of the module corresponding to the navigation.
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:
##[Related recommendations]1. 2.JavaScript Chinese Reference Manual
3.php.cnDugu Jiujian (3)-JavaScript Video Tutorial
The above is the detailed content of Javascript implementation of navigation anchor scrolling effect example. For more information, please follow other related articles on the PHP Chinese website!