Bootstrap 4 Smart Scroll

跟風遠走 提交于 2021-01-28 08:58:56

问题


I'm using this basic tutorial to show/hide a standard BS4 navbar on scroll, and it works great for desktop.

However, on mobile the navbar is acting a little strange when scrolling down, then going back to the top. Once back to the top, the navbar hides again.

I suspect the issue has something to do with scrollTop() but can't seem to troubleshoot this one.

Here's my JS:

    if ($('.smart-scroll').length > 0) { // check if element exists
        var last_scroll_top = 0;
        $(window).on('scroll', function() {
            var scroll_top = $(this).scrollTop();
            if(scroll_top < last_scroll_top) {
                $('.smart-scroll').removeClass('scrolled-down').addClass('scrolled-up');
            } else {
                $('.smart-scroll').removeClass('scrolled-up').addClass('scrolled-down');
            }
            last_scroll_top = scroll_top;
            /* Tried to catch for scroll_top zero, but doesn't help */
            if(scroll_top == 0) $('.smart-scroll').removeClass('scrolled-up');

        });
    }

And, here's my CSS:

.smart-scroll {
    position: fixed !important;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1000;
    transition: all 0.3s ease-in-out;
}
.scrolled-down {transform:translateY(-100%);}
.scrolled-up {transform:translateY(0);} 

I also tried incorporating this stackoverflow and still couldn't get it working.

Any ideas to get this operational on mobile?


回答1:


Had something similar in my practices. Took code from there and adapted to your case.

if ($('.smart-scroll').length > 0) {

        var lastScrollTop = 0;
        $(window).scroll(function() {    

            var scroll_top = $(window).scrollTop();

            if (scroll_top > 1) { // think, this will work a little bit better to catch scrolltop more then 0(1)
                $(".smart-scroll").addClass("stick");
            } else { 
                $(".smart-scroll").removeClass("stick");
            }

            if (scroll_top > lastScrollTop){
                $(".smart-scroll").removeClass("scrolled-up");                      
            } else {
                $(".smart-scroll").addClass("scrolled-up");
            }                       
            lastScrollTop = st;

    });

}   

And CSS

.smart-scroll {
    position: fixed !important;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1000;
    transition: all 0.3s ease-in-out;
    transform:translateY(0);
}
.stick {transform:translateY(-100%);}
.scrolled-up {transform:translateY(0) !important;} 


来源:https://stackoverflow.com/questions/61760693/bootstrap-4-smart-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!