简体   繁体   English

如何修改此导航栏以仅在 100 像素后向下滚动时隐藏?

[英]How to modify this navbar to hide on scroll down only after 100px?

I currently have a navbar that on scroll down disappears and on scroll up reappears again (and is always visible when at the top of the page).我目前有一个导航栏,向下滚动消失,向上滚动再次出现(并且在页面顶部始终可见)。

This works fine on desktop - the nav always shows when the page is at the top, but on mobile devices glitches and disappears completely when at the top of the page.这在桌面上运行良好 - 当页面位于顶部时,导航始终显示,但在移动设备上,当位于页面顶部时,导航会出现故障并完全消失。

How would I amend this to be visible on scroll down for the first 100px, then disappear until user scrolls up?我将如何修改它以在前 100px 向下滚动时可见,然后消失直到用户向上滚动?

var prevScrollpos = window.pageYOffset;
window.onscroll = function () {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById('mainNav').style.top = '0';
  } else {
    document.getElementById('mainNav').style.top = '-100px';
  }
  prevScrollpos = currentScrollPos;
};

Solution解决方案

var prevScrollpos = window.pageYOffset;
window.onscroll = function () {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos || currentScrollPos <= 100) {
     document.getElementById('mainNav').style.top = '0';
  } else {
     document.getElementById('mainNav').style.top = '-100px';
   }
  prevScrollpos = currentScrollPos;
};

You can style element for scrolled and non-scrolled page.您可以为滚动和非滚动页面设置元素样式。 See the simple solution below:请参阅下面的简单解决方案:

 function update() { window.document.body.setAttribute('data-scrolled', window.pageYOffset > 100? 'Y': 'N'); } window.onscroll = update; window.onresize = update; update();
 body { height: 4000px; } #test { position: fixed; } body[data-scrolled="N"] #test { color: blue; } body[data-scrolled="Y"] #test { color: red; }
 <div id="test">Please scroll the page</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM