常见的开发页面中可能会有这么一个需求,页面中会有多个模块,每个模块对应一个导航,当页面滚动到某个模块时,对应的模块导航需要加上一个类用于区分当前用户所浏览区域。
假设结构如下:
<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>
页面滚动时导航定位
js代码如下:
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; } } });
效果如下:
不难看出,基本原理就是在window滚动的时候,依次将模块从后向前遍历,如果window的滚动高度大于或等于当前模块的距页面顶部的距离,则将当前模块对应的导航突出显示,并且不再继续遍历
点击导航定位页面
除了这种需求外,还有另一种需求,就是点击导航定位到导航所对应模块的顶部。
代码如下:
$navs.on('click', function(e) { e.preventdefault(); $('html, body').animate({ 'scrolltop': $($(this).attr('href')).offset().top }, 400); });
效果如下:
以上基本上满足了业务的基本需求,这是工作中总结的经验,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
2016年信息安全工程师综合知识第11-15题解析【建群网培信息安全工程师】
网友评论