jQuery定位导航滚动3

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <style type="text/css">
    * {
        margin: 0;
        padding: 0;
    }
    a{ text-decoration: none; color: #333; height: 35px; line-height: 35px; }

    .section {
        height: 500px;
        border-bottom: 1px solid red;
    }

    nav {
        position: fixed;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
    }

    nav a {
        display: block;
    }
    .current{ color: red; }
    </style>
    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>

<body>
    <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 type="text/javascript">
    $(function() {
        var $navs = $('nav a'), // 导航
            $sections = $('.section'), // 模块
            $window = $(window),
            navLength = $navs.length - 1;
            console.log(navLength)

        $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;
                }
            }
        });
    })
    </script>
</body>

</html>

效果图:

原文地址:https://www.cnblogs.com/huanghuali/p/8432347.html