jQuery Mobile: 滚动页面时隐藏标题栏并在向上滚动时显示

5

在许多移动应用程序中,我们经常看到当用户向下滚动页面时,页眉消失,当他们向上滚动页面时,页眉出现。我们如何在jQuery Mobile中实现这一点?(我将在下面回答自己的问题)

2个回答

8
/**
 * Header scroll control
 * When the user scrolls down the page hide the header, when they scroll up show it.
 */
var lastScrollPosition;

$(document).scroll( function() {
  var scrollPosition = $(this).scrollTop();

  // Scrolling down
  if (scrollPosition > lastScrollPosition){
    // If the header is currently showing
    if (!$('[data-role=header].ui-fixed-hidden').length) {
      $('[data-role=header]').toolbar('hide');
    }
  } 

  // Scrolling up
  else {
    // If the header is currently hidden
    if ($('[data-role=header].ui-fixed-hidden').length) {
      $('[data-role=header]').toolbar('show');
    }
  }

  lastScrollPosition = scrollPosition;  
});

0

Sean Bannister的解决方案的变体,使用Bootstrap 4并带有过渡效果:

JS:

    var lastScrollPosition;
    var headerHeight;
    $(document).scroll( function() {
        var scrollPosition = $(this).scrollTop();
        if (scrollPosition > lastScrollPosition){ // Scrolling down
            if ($('.sticky-top.show').length) {
                $('.sticky-top').removeClass('show');
                headerHeight = -$('.sticky-top').height() + 'px';
                $('.sticky-top').css('top', headerHeight);
            }
        } else {  // Scrolling up
            if (!$('.sticky-top.show').length) {
                $('.sticky-top').addClass('show');
                $('.sticky-top').css('top', '0');
            }
        }
        lastScrollPosition = scrollPosition;
    });

CSS:

.sticky-top { transition: top 0.3s; }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接