滚动事件的动画菜单

时间:2016-07-05 05:51:09

标签: html css

我使用以下代码创建隐藏/显示导航

基于http://jsfiddle.net/mariusc23/s6mLJ/31/

我的代码

  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;
}

但是我希望它在用户向上或向下滚动时动画显示,然后在完成scolling时动画回来

1 个答案:

答案 0 :(得分:1)

这可能要简单得多。

例如:

var didScroll;

$(window).scroll(function(event) { didScroll = true; });
setInterval(function() {
  if (didScroll) {
      $('header').removeClass('nav-down').addClass('nav-up');
      didScroll = false;
  }else{
      $('header').removeClass('nav-up').addClass('nav-down');
  }
}, 400);
body {
    padding-top: 40px;
}

header {
    background: #f5b335;
    height: 40px;
    position: fixed;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
}

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

main {
   background:url(
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAPklEQVQYV2O8dOnSfwYg0NPTYwTRuAAj0QqxmYBNM1briFaIzRbi3UiRZ75uNgUHGbfvabgfsHqGaIXYPAMAD8wgC/DOrZ4AAAAASUVORK5CYII=
   ) repeat;
    height: 2000px;
}

footer { background: #ddd;}
* { color: white}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="nav-down">
    This is your menu.
</header>
<main>
    This is your body.
</main>
<footer>
    This is your footer.
</footer>