简体   繁体   English

当用户停止滚动时,使隐藏的 header 重新出现

[英]Make hidden header reappear when user stops scrolling

I'm currently using the code below to hide the header when the user scrolls down, and show it again when they scroll up.我目前正在使用下面的代码在用户向下滚动时隐藏 header,并在他们向上滚动时再次显示。 It's functioning well, however I would like to append it so that, as well as reappearing on scroll-up, the header also reappears when the user has stopped scrolling for a specified amount of time.它运行良好,但是我想 append 它,以便在向上滚动时重新出现,header 在用户停止滚动指定的时间量时也会重新出现。

Any help much appreciated.非常感谢任何帮助。

Current code -当前代码 -

// Hide Header on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
didScroll = true;
});

setInterval(function() {
if (didScroll) {
    hasScrolled();
    didScroll = false;
}
}, 50);

function hasScrolled() {
var st = $(this).scrollTop();

// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
    return;

// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
    // Scroll Down
    $('header').removeClass('nav-down').addClass('nav-up');
} else {
    // Scroll Up
    if(st + $(window).height() < $(document).height()) {
        $('header').removeClass('nav-up').addClass('nav-down');
    }
}

lastScrollTop = st;
}

You could create a function which will check if the user stops scrolling.您可以创建一个 function 来检查用户是否停止滚动。 Then you could handle your logic to display your header in the callback function.然后你可以处理你的逻辑在回调 function 中显示你的 header。

...
// @param  {Function} callback The callback function to run after scrolling
// @param  {Integer}  refresh  How long to wait between scroll events [optional]
function scrollStop (callback, refresh = 60) {
    // Make sure a valid callback was provided
    if (!callback || typeof callback !== 'function') return;

    // Setup scrolling variable
    let isScrolling;

    // Listen for scroll events
    window.addEventListener('scroll', function (event) {

        // Clear our timeout throughout the scroll
        window.clearTimeout(isScrolling);

        // Set a timeout to run after scrolling ends
        isScrolling = setTimeout(callback, refresh);

    }, false);

}

scrollStop(function () {
    // logic to display header here
    $('header').removeClass('nav-up').addClass('nav-down');
    console.log('Scrolling has stopped.');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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