• 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

  • 相关阅读:
    MySQL体系结构
    Java线程池ThreadPoolExecuter:execute()原理
    Java Thread 如何处理未捕获的异常?
    SSL/TSL握手过程详解
    LockSupport HotSpot里park/unpark的实现
    JAVA 对象内存结构
    JAVA 线程状态转换
    Spring源码解析(四)Bean的实例化和依赖注入
    Spring源码解析(五)循环依赖问题
    Spring源码解析(三)BeanDefinition的载入、解析和注册
  • 原文地址:https://www.cnblogs.com/widgetbox/p/8629481.html
Copyright © 2020-2023  润新知