欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-02-27 14:33:00|栏目:JavaScript代码|点击:

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

假设结构如下:

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

效果如下:

上一篇:JS简单判断函数是否存在的方法

栏    目:JavaScript代码

下一篇:select下拉框插件jquery.editable-select详解

本文标题:Javascript实现页面滚动时导航智能定位

本文地址:http://www.codeinn.net/misctech/71007.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有