简体   繁体   中英

Navbar Position remain fixed when scroll back to top

Actually am trying to achieve a sticky nav when scrolled and i use the javascript if...else statement to add a class of .sticky to the #navbar if the onscroll is greater than the #navbar offsetTop, else remove the class of .sticky and i add position: fixed; and width: 100%; and top: 0; to the .sticky , and fortunately these add class of .sticky to #navbar if the scroll is greater than the #navbar offsetTop

MY PROBLEM IS :- When scroll is less than the #navbar offsetTop the .sticky class doesn't remove and the #navbar remain fixed when scroll back to the top, how do i fixed it that my navbar will be back to normal when scroll is less than #navbar offsetTop..

HTML

<header>
    <p>FaceMash</p>
    <div id="headnotify">
        <a href="#">🔔</a>
        <a href="#">🔇</a>
        <a href="#">📶</a>
        <a href="#">📧</a>
    </div>  
</header>

<div id="navbar">
    <a href="#">Home</a>
    <a href="#">Explore</a>
    <a href="#">Discover</a>
    <a href="#">Filter</a>
    <a href="#">Docs</a>
    <a href="#">More</a>
</div>

<section>
    <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto obcaecati exercitationem nam fugiat, ab molestias quo saepe, sed iste doloribus earum, expedita quia nobis quidem quasi aliquid eos ullam! Qui fugiat, dolores quasi velit quae maxime blanditiis id. Aspernatur, omnis laudantium autem voluptate quibusdam dolor, alias tempora nam, blanditiis hic nihil iure saepe recusandae. Harum officia maxime laborum quia explicabo laudantium odit quisquam alias libero natus, voluptas voluptate nisi perspiciatis quam iusto rem atque officiis vitae cumque ad dolore, debitis labore. Natus ea expedita cupiditate, deserunt provident, laboriosam error beatae inventore consequuntur necessitatibus facere. Suscipit quis corrupti alias dolor ex error natus, expedita sed, voluptatibus aliquam quisquam earum voluptate rem animi omnis harum placeat quos unde! Debitis tempora, magni ex, nostrum ipsam consequuntur. Eaque, dolorem, tempore totam minus odio pariatur, veniam ad fugiat, incidunt harum dolorum quibusdam error cumque quae. Ipsam, necessitatibus nesciunt provident. Aliquid aut, dolorum! Dolor earum laborum repellendus at iure maiores quas enim reprehenderit ex ullam sequi possimus autem incidunt, porro vero quibusdam consectetur aspernatur accusamus et consequatur ipsum fugit. Totam officia nesciunt, accusantium sapiente quis placeat voluptatum, itaque repellat ratione. Non quis saepe eaque fugiat aliquam sit. Rerum aspernatur culpa, adipisci illum ea distinctio debitis quasi omnis sequi, natus, nulla. Voluptatum vel, quidem hic, autem dolore modi? Beatae quod sit, neque ex ab, tempore quam vel culpa ea quasi corporis vero, quaerat ipsam necessitatibus rem magnam, earum eius dignissimos ducimus exercitationem eveniet! Consectetur minus vitae, voluptatum suscipit. Voluptatibus esse aut eaque delectus. Consequatur molestias quam voluptatibus, quidem necessitatibus dolorem harum explicabo ut quas, amet magnam voluptatum illum quia laborum in voluptate expedita blanditiis. Sapiente fuga culpa maiores eum eligendi eaque sit explicabo vitae fugiat soluta, rerum vel atque perferendis repellat fugit mollitia ab, adipisci inventore? Quidem tempore commodi hic. Voluptatem nostrum possimus, asperiores minima animi numquam.
    </p>
</section>

CSS

body{
    margin: 0;
    padding: 0;
    font-family: arial;
}

#navbar{
    display: flex;
    height: 50px;
    color: #fff;
    -ms-align-items: center;
    align-items: center;
    background-color: gray;
}

#navbar a{
    padding: 15px 30px;
    color: #fff;
    text-decoration: none;
}

#navbar a:hover{
    background-color: rgba(0,0,0,.1);
}

header{
    height: 100px;
    display: flex;
    -ms-align-items: center;
    align-items: center;
}

header p{
    font-size: 1.8em;
    color: gray;
    margin-left: 30px;
}

header #headnotify{
    margin-left: auto;
    margin-right: 50px;
    display: flex;
}

header #headnotify a{
    text-decoration: none;
    padding: 10px 25px;
    font-size: 1.5em;
}

header #headnotify a:hover{
    background-color: #f1f1f1;
}


section{
    width: 90%;
    border: 1px solid gray;
    padding: 30px;
    margin: 30px auto ;
}

section p{
    font-size: 1.4em;
    line-height: 30px;
    color: gray;
}

.sticky{
    position: fixed;
    width: 100%;
    top: 0;
}

JAVASCRIPT

<script type="text/javascript">
    const navbar = document.getElementById("navbar");

    function scrollNav() {
        if (window.pageYOffset >= navbar.offsetTop) {
            navbar.classList.add('sticky');
        }else {
            navbar.classList.remove('sticky');
        }
    }

    window.onscroll = function () {
        scrollNav();
    }
</script>

The issue is that your function constantly recalculates the offset because your event is bound to onscroll . What this means is that when it is set to sticky , the offset becomes unpredictable. You can fix this by pulling out the offsetTop variable outside of the function, so it is calculated only once.

var navbar = document.getElementById("navbar");
var navbarOffset = navbar.offsetTop;

window.onscroll = function () {
    window.pageYOffset >= navbarOffset ? navbar.classList.add('sticky') : navbar.classList.remove('sticky')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM