jQuery Mobile:将页眉隐藏在向下滚动并在向上滚动时显示

时间:2014-01-21 04:37:17

标签: jquery-mobile

我们在许多移动应用中看到的一个常见问题是当用户向下滚动页面时标题消失,当它们向上滚动页面时,标题会出现。我们如何在jQuery Mobile中实现这一目标? (我在下面回答我自己的问题)

2 个答案:

答案 0 :(得分:7)

/**
 * 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;  
});

答案 1 :(得分:0)

使用Bootstrap 4并进行过渡的Sean Bannisters解决方案的变化:

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