Javascript如何实现页面滚动时导航智能定位

发布时间:2021-04-25 09:47:27 作者:小新
来源:亿速云 阅读:240

小编给大家分享一下Javascript如何实现页面滚动时导航智能定位,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

Java有哪些集合类

Java中的集合主要分为四类:1、List列表:有序的,可重复的;2、Queue队列:有序,可重复的;3、Set集合:不可重复;4、Map映射:无序,键唯一,值不唯一。

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

假设结构如下:

<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;
    }
  }
});

效果如下:

Javascript如何实现页面滚动时导航智能定位

不难看出,基本原理就是在window滚动的时候,依次将模块从后向前遍历,如果window的滚动高度大于或等于当前模块的距页面顶部的距离,则将当前模块对应的导航突出显示,并且不再继续遍历

点击导航定位页面

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

代码如下:

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

效果如下:

Javascript如何实现页面滚动时导航智能定位

看完了这篇文章,相信你对“Javascript如何实现页面滚动时导航智能定位”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 监听页面滚动及滚动到指定位置
  2. JS 侧栏导航点击定位页面内容位置及滚动条滚动改变导航元素对应状态

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js

上一篇:JavaScript如何实现简单的四则运算计算器

下一篇:JavaScript如何实现省市县三级级联特效

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》