导航锚点滑动定位

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

效果如下:

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

相关推荐
Jonathan Star20 小时前
跨域处理的核心是解决浏览器的“同源策略”限制,主流方案
javascript·chrome·爬虫
果粒chenl21 小时前
React学习(四) --- Redux
javascript·学习·react.js
Never_Satisfied21 小时前
在JavaScript / HTML中,div容器在内容过多时不显示超出的部分
开发语言·javascript·html
ZHOUYUANN1 天前
我用JavaScript复刻了某宝的小游戏动物大迁徙消消乐
前端·javascript·游戏开发
Asort1 天前
JavaScript设计模式(十三)——责任链模式:构建灵活高效的请求处理链
前端·javascript·设计模式
摸着石头过河的石头1 天前
JavaScript继承与原型链:揭开对象传承的神秘面纱
前端·javascript
用户6387994773051 天前
我把我的 monorepo 迁移到 Bun,这是我的真实反馈
javascript·架构
用户57973883973151 天前
JavaScript(Node.JS) 使自定义类可以通过下标访问内部可迭代值
javascript
博客zhu虎康1 天前
Element中 el-tree 如何隐藏 Tree 组件中的父节点 Checkbox
javascript·vue.js·elementui
欧阳天1 天前
http环境实现通知
前端·javascript