在滚动上隐藏标题,但是当您到达底部并向上滚动标题显示时

时间:2018-03-26 23:13:14

标签: javascript html

我不完全确定如何提出这个问题所以我不确定这个问题是否已经存在..

我向你向下滚动后隐藏了一个标题..



 let prevScrollpos = window.pageYOffset;
 window.onscroll = function() {
    let currentScrollpos = window.pageYOffset;
      if (prevScrollpos > currentScrollPos) {
        const header = document.getElementById('app-program-header');
        header.style.top = '0';
    } else {
        const header = document.getElementById('app-program-header');
        header.style.top = '-50px';
  }
  prevScrollpos = currentScrollpos;
};

<div style="height: 50px; width: 100%; background-color: black; position: absolute;" id="app-program-header">
</div>
<div style="height: 150vh; background: pink; width: 100%;" class="body">
</div>
&#13;
&#13;
&#13;

但我想要发生的事情是,如果你到达页面的底部,然后向上滚动,我希望标题重新进入..我不完全确定我将如何做这样的事情

修改

由于移动设备的滚动方式,我需要能够将向上滚动的偏移量改为10,20px,因此当您向上滚动时标题不会立即返回

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

我添加var direction来判断向上/向下滚动,

<div id="app-program-header">position=fixed

然后使用style.display来确定显示标题,而不是style.top

&#13;
&#13;
var prevScrollpos = 0;
var maxScrollpos = 0;
window.onscroll = function() {
  let currentScrollpos = window.pageYOffset;
  let direction = currentScrollpos - prevScrollpos;
  let header = document.getElementById('app-program-header');
  if(direction<0 && (maxScrollpos - currentScrollpos) > 50){ //if minus, scroll up
    header.style.top = '5px';
    header.style.display = 'block';
  }
  else{
    maxScrollpos = currentScrollpos > maxScrollpos ? currentScrollpos : maxScrollpos
    if (prevScrollpos < 50) {
        header.style.display = 'block';
        maxScrollpos = 0;
    } else {
        header.style.display = 'none';
    }
  }
  prevScrollpos = currentScrollpos;
};
&#13;
<div id="app-program-header" style="top:5px;height:20px;display:block;background-color:green;position:fixed;">
header
</div>
<div style="height:800px;margin-top:40px;">
body
</div>
&#13;
&#13;
&#13;