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:
section1
section2
section3
section4
section5
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!