Javascript实现导航锚点滚动效果实例

本篇文章主要介绍了Javascript实现页面滚动时导航智能定位,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

 

常见的开发页面中可能会有这么一个需求,页面中会有多个模块,每个模块对应一个导航,当页面滚动到某个模块时,对应的模块导航需要加上一个类用于区分当前用户所浏览区域。

假设结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< 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 >

页面滚动时导航定位

js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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的滚动高度大于或等于当前模块的距页面顶部的距离,则将当前模块对应的导航突出显示,并且不再继续遍历

点击导航定位页面

除了这种需求外,还有另一种需求,就是点击导航定位到导航所对应模块的顶部。

代码如下:

1
2
3
4
5
6
$navs.on( 'click' , function (e) {
   e.preventDefault();
   $( 'html, body' ).animate({
     'scrollTop' : $($( this ).attr( 'href' )).offset().top
   }, 400);
});

效果如下:

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值