jQuery Mobile:使标题在向下滚动时隐藏并在向上滚动时显示

问题描述 投票:5回答:2

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

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 Bannisters解决方案的变化,使用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; }
© www.soinside.com 2019 - 2024. All rights reserved.