js 滚动导航实现定位

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>js 滚动导航实现定位</title>

    <style>

        body {

            margin: 0;

            text-align: center;

            font-family: sans-serif;

        }

        .fixed {

            position: fixed;

            top: 0;

        }

        .sticky {

            width: 100%;

            background: #F6D565;

            padding: 25px 0;

            text-transform: uppercase;

        }

    </style>

</head>

<body>

    <p style="margin-bottom:100px;">滚动此页面。</p>

    <div class="sticky"><h3>头部</h3></div>

    <p style="margin-top:500px;">内容1</p>

    <p style="margin-top:500px;">内容2</p>

    <p style="margin-top:500px;">底部</p>

    <script>

        var sticky = document.querySelector('.sticky');

        var origOffsetY = sticky.offsetTop;

        function onScroll(e) {

            window.scrollY >= origOffsetY ? sticky.classList.add('fixed') : sticky.classList.remove('fixed');

        }

        document.addEventListener('scroll', onScroll);

    </script>

</body>

</html>
发布了32 篇原创文章 · 获赞 40 · 访问量 5982

猜你喜欢

转载自blog.csdn.net/qq_43102934/article/details/102134273