美文网首页
js 滚动导航实现定位

js 滚动导航实现定位

作者: 熙如意Xiry8881 | 来源:发表于2019-10-05 10:19 被阅读0次

<!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>

相关文章

网友评论

      本文标题:js 滚动导航实现定位

      本文链接:https://www.haomeiwen.com/subject/qapepctx.html