[英]Make hidden header reappear when user stops scrolling
我目前正在使用下面的代碼在用戶向下滾動時隱藏 header,並在他們向上滾動時再次顯示。 它運行良好,但是我想 append 它,以便在向上滾動時重新出現,header 在用戶停止滾動指定的時間量時也會重新出現。
非常感謝任何幫助。
當前代碼 -
// 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;
}
您可以創建一個 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.