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;">Scroll this page.</p>
    <div class="sticky"><h3>Super amazing header</h3></div>
    <p style="margin-top:500px;">Still there?</p>
    <p style="margin-top:500px;">Yep!</p>
    <p style="margin-top:500px;">Scroll so hard!</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>

 

posted @ 2017-11-30 16:38  <_/>  阅读(1656)  评论(0编辑  收藏  举报