我有以下脚本(如摘录所示),当用户向下滚动时隐藏我的菜单(nav),而在向上滚动时将其带回。

但是它不起作用,我不确定问题出在哪里



var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('nav').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
        $('nav').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('nav').removeClass('nav-up').addClass('nav-down');
        }}
    lastScrollTop = st;
}

.nav-up { top: -100px; }

#s-nav {
	position: fixed;
	z-index: 999;
	top: 0;
	width: 100%; height: 100px;
	padding-top: 25px;
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="s-nav" class="nav-down">
  <p>navigation</p>
</nav>

最佳答案

这是因为id is more specify than class

您可以使用调试器自己找到它:
javascript - 向上滚动时隐藏菜单-LMLPHP



jQuery(function($) {
  var didScroll;
  var lastScrollTop = 0;
  var delta = 5;
  var navbarHeight = $('nav').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
      $('nav').removeClass('nav-down').addClass('nav-up');
    } else {
      // Scroll Up
      if (st + $(window).height() < $(document).height()) {
        $('nav').removeClass('nav-up').addClass('nav-down');
      }
    }
    lastScrollTop = st;
  }
});

#s-nav.nav-up {
  top: -100px;
}
#s-nav {
  position: fixed;
  top: 0;
  width: 100%;
  height: 100px;
  padding-top: 25px;
  transition: top 0.3s;
}
.content {
  height: 2000px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="s-nav" class="nav-down">
  ... nav content ...
</nav>
<div class='content'>
  content
</div>

关于javascript - 向上滚动时隐藏菜单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38175910/

10-12 06:47