HTML
<div id="fixedNav">header</div>
<div style="height:800px"></div>
CSS
#fixedNav {
position: sticky;
height: 50px;
background: black;
color: #fff;
display: flex;
align-items: center;
top: 0;
transition: all 0.3s ease;
}
#fixedNav.nav-up {
top: -50px;
transition: 0.2s;
}
JS
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('#fixedNav').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('#fixedNav').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('#fixedNav').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
See the Pen 스크롤시 반응하는 헤더 by Juyeon (@Juyeon) on CodePen.