jq 导航跟随 模拟京东手机端

想做一个导航跟随,但是代码都要下载,自己简单些了一个,css都放html里面了,所以也不用下载直接新建html,然后粘贴,点开就是导航跟随效果

效果如图

<!DOCTYPE html>
<html>
  <head>
    <title>导航跟随</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
  </head>
 <style>
        #nav {
            display: -webkit-box;
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            line-height: 30px;
            font-size: 14px;
            width: 100%;
            position: fixed;
            top: 0px;
            left: 0px;
            z-index: 100;
            border-bottom: 1px solid #e5e5e5;
            border-top: 1px solid #e5e5e5;
            min-height: 44px;
            background: #000;
        }

            #nav a {
                display: block;
                position: relative;
                width: 25%;
                line-height: 44px;
                text-align: center;
               
                color: #fff;
            }

                #nav a.active {
                    color: #fff;
 background: red;
                }

        #main {
            padding-top: 44px;
        }
</style>
 <script>
        $(window).load(function () {
            $('html, body').animate({ scrollTop: 0 }, 200);
            var nav = $("#nav");
            var mainPage = $(".mainPage");
            var mainTopArr = new Array();
            for (var i = 0; i < mainPage.length; i++) {
                var top = mainPage.eq(i).offset().top;
                mainTopArr.push(top);
            }
            $(window).scroll(function () {
                var scrollTop = $(this).scrollTop();
               
                var k;
                for (var i = 0; i < mainTopArr.length; i++) {
                    if (scrollTop + 144 >= mainTopArr[i]) {
                        k = i;
                    }
                }
                nav.find("a").eq(k).addClass("active").siblings().removeClass("active");
            });
            nav.find("a[href^='#']").click(function (e) {
                e.preventDefault();
                $('html, body').animate({ scrollTop: $(this.hash).offset().top - 144 }, 200);
            });
        });
    </script>
  <body>
    <div id="nav">
      <a href="#imgdetails" class="active">商品</a>
          <a href="#specifications">规格</a>
          <a href="#reviews">评价</a>
          <a href="#description">详情</a>
    </div>
 <div id="main">
        <div class="mainPage" id="imgdetails"style="height:500px">我是第一块的内容</div>
    <div class="mainPage" id="specifications" style="height:500px">我是第二块的内容</div>
    <div class="mainPage" id="reviews" style="height:500px">我是所有评论啦,来看评论</div>
    <div class="mainPage" id="description" style="height:500px">我是介绍,来看介绍</div>
  </body>
</html>

本来是想用document.ready,但是应用到实际中有页面包含了很多绝对定位的元素,定位并不准确。

原文地址:https://www.cnblogs.com/yes-you-can/p/9348233.html