我目前正在使用下面的代码在用户向下滚动时隐藏标题,并在他们向上滚动时再次显示。它运行良好,但是我想附加它,以便在向上滚动时重新出现,当用户停止滚动指定的时间时,标题也会重新出现。
非常感谢任何帮助。
当前代码 -
// 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; }
您可以创建一个函数来检查用户是否停止滚动。然后您可以处理您的逻辑以在回调函数中显示您的标题。
... // @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.'); });