简体   繁体   中英

Show Navbar only when scrolling to top on mobile (Bootstrap 4)

I want to show the navbar on mobile only if the user scrolls to the top of the page.

At the moment it's stuck on the top everytime the user scrolls down or up. I'm using the code from here: https://stackoverflow.com/a/42250478/1788961 Here's the example: https://www.codeply.com/go/H7ZKuxKTKm

My JS code:

new IntersectionObserver(function(e,o){
        if (e[0].intersectionRatio > 0){
            document.documentElement.removeAttribute('class');
        } else {
            document.documentElement.setAttribute('class','stuck');
        };
    }).observe(document.querySelector('.trigger'));

Edit: to clarify what I want:

I don't want the navbar on mobile to be sticky. It should scroll away with the rest of the site. But if I'm on the bottom of the page and I scroll to the top, the navbar should appear on the top and stay there as long as I scroll to the top.

The class "sticky-top" makes the navbar stick to the top of the page even if the user scrolls. Taking it off fixes your issue.

Example here: https://www.codeply.com/go/wWKGkjYdGy

You would use a CSS media query only apply position:sticky on mobile (ie; <768px)...

.sticky-top {
    position: static;
}

@media (max-width:768px) {
    .sticky-top {
        transition: all 0.25s ease-in;
        position: sticky;
    }

    .stuck .sticky-top {
        background-color: #222 !important;
        padding-top: 3px !important;
        padding-bottom: 3px !important;
    }
}

https://www.codeply.com/go/1b80jD3Tpg

If you want the opposite effect (non-sticky navbar on mobile) just reverse the media query to min-width instead of max-width...

@media (min-width:768px) {
    .sticky-top {
        transition: all 0.25s ease-in;
        position: sticky;
    }

    .stuck .sticky-top {
        background-color: #222 !important;
        padding-top: 3px !important;
        padding-bottom: 3px !important;
    }
}

https://www.codeply.com/go/4RtpB24k23

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