导航栏仅在iOS中向上滚动时显示

时间:2014-05-04 17:21:15

标签: javascript ios touch mobile-safari

当用户向上滚动时,我使用Marius Craciunoiu technique显示我的整个导航栏。

所以,这是我的 JavaScript (使用jQuery)代码:

var delta, didScroll, lastScrollTop, navbarHeight;

delta = 5;
lastScrollTop = 0;
navbarHeight = $('.navbar').outerHeight();

$(window).on('scroll touchmove', function() {
  didScroll = true;
});

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

function hasScrolled() {
  var scrollTop = $(this).scrollTop();

  if (Math.abs(lastScrollTop - scrollTop) <= delta) { return; }

  if (scrollTop > lastScrollTop && scrollTop > navbarHeight) {
    $('.navbar').addClass('scrolling');
  } else {
    if (scrollTop + $(window).height() < $(document).height()) {
      $('.navbar').removeClass('scrolling');
    }
  }

  lastScrollTop = scrollTop;
}

为了更轻松,我将代码发布在http://jsfiddle.net/caio/7HrK7/上。如果您想在iOS中进行测试,请使用http://fiddle.jshell.net/caio/7HrK7/show/light/网址。

视频: http://hiperload.com/s/ua5k53n0x/d.mp4?inline

您可以看到,我的代码适用于台式机和Android手机。但是在iOS上,它需要一个触摸事件来响应滚动事件仍然发生,否则它只会在最后执行。我尝试添加touchmove事件,但没有成功。你能救我吗?

1 个答案:

答案 0 :(得分:1)

看起来iOS在滚动时会暂停所有计时器。也许你在运行这项技术时会有一些运气:

iOS 6 js events function not called if has setTimeout in it

或者,您可以直接在hasScrolled()上运行touchmove。这似乎会导致一些闪烁(至少在我的iPad上),所以你可能需要找出一种不同的方式来设置滚动条的动画:

$(window).on('touchmove', function() {
  hasScrolled();
});

在这里看一个小提琴: http://jsfiddle.net/mariusc23/7HrK7/13/

如果您找到解决方案,请告诉我,以便我可以更新帖子。我也会花些时间在上面。谢谢阅读。 :)