Javascript implementation of navigation anchor scrolling effect example

零下一度
Release: 2017-05-08 10:29:01
Original
3563 people have browsed it

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

Copy after login

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; } } });
Copy after login

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); });
Copy after login

The effect is as follows:

##[Related recommendations]

1.

Free js online video tutorial

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!