导航锚点滑动定位

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

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

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

假设结构如下:

复制代码
  <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代码如下:

ini 复制代码
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的滚动高度大于或等于当前模块的距页面顶部的距离,则将当前模块对应的导航突出显示,并且不再继续遍历

点击导航定位页面

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

代码如下:

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

效果如下:

以上基本上满足了业务的基本需求,这是工作中总结的经验,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关推荐
安冬的码畜日常1 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
太阳花ˉ1 小时前
html+css+js实现step进度条效果
javascript·css·html
john_hjy2 小时前
11. 异步编程
运维·服务器·javascript
风清扬_jd2 小时前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome
yanlele2 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范
It'sMyGo2 小时前
Javascript数组研究09_Array.prototype[Symbol.unscopables]
开发语言·javascript·原型模式
xgq3 小时前
使用File System Access API 直接读写本地文件
前端·javascript·面试
李是啥也不会3 小时前
数组的概念
javascript
无咎.lsy3 小时前
vue之vuex的使用及举例
前端·javascript·vue.js