jQuery定位导航滚动3

Posted 前端HL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

效果图:

 

以上是关于jQuery定位导航滚动3的主要内容,如果未能解决你的问题,请参考以下文章

jQuery Tocify 定位导航

固定导航上所有div上方的Jquery滑块

js实现滚动定位

jq实现滚动定位

12个用得着的 JQuery 代码片段

jQuery 平滑滚动片段以不同的速度工作