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


 

遇到的问题:

在做官网的时候,需要滚动定位的区块的图片不确定,无法确定用户浏览区域对应的模块导航

之前的解决方案是:

通过定位滚动条的位置来判断用户浏览区域对应的模块导航,这种方法的弊端是,区块的高度不确定时就无法计算滚动条的位置来判断;

优化方案:

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

以下是DEMO

<!-- html -->
<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>
 
<script>
<!-- 页面滚动时导航定位 -->
 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;
      }
    }
  });
<!-- 点击导航定位页面 -->
  $navs.on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
    'scrollTop': $($(this).attr('href')).offset().top
    }, 400);
  });
</script>

  

write by  tuantuan


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM