隐藏导航栏向下滚动并在向上滚动时显示

时间:2018-04-09 04:14:57

标签: javascript jquery css

我希望在向下滚动时隐藏我的顶部导航栏,并在向上滚动时显示此website导航栏。目前,我正在使用此代码,但它无法正常工作,它在向下滚动时有效,但在向上滚动时无效。



<script type="text/javascript">

// Hide #main-nav on on scroll down
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('#main-nav').outerHeight();

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

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

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 .MagicMenu-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('#main-nav').slideDown(500);
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('#main-nav').slideUp(500);
        }
    }
    
    lastScrollTop = st;
}
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

不需要setInterval(function() { ...,因为即使用户没有滚动也要不停地执行该功能,将其替换为滚动的eventListener

你的#main-nav只是向上和向下滑动,你需要根据滚动更改它的位置,以便在滑下时让我看到,

尝试避免使用jquery动画并尽可能使用css过渡效果,这对性能有好处,

这是一个例子(没有jQuery),根据您的需要进行调整:

let nav = document.querySelector('#nav');
let lastScrollTop;

window.addEventListener("scroll", function() {  // listen for the scroll 
  var st = window.pageYOffset || document.documentElement.scrollTop;
  if (st > lastScrollTop) 
    nav.style.opacity = 0; // hide the nav-bar when going down
  else 
    nav.style.opacity = 1; // display the nav-bar when going up
  
  lastScrollTop = st;

  nav.style.top = `${st}px`; // set the position of the nav-bar to the current scroll
}, false);
* {
  box-sizing: border-box;
}

body {
  height: 1000px;
  padding: 0;
  margin: 0;
}

#nav {
  width: 100%;
  height: 50px;
  background: blue;
  position: absolute;
  transition: opacity 0.5s linear;
}
<div id="nav">

</div>