繁体   English   中英

在滚动功能上隐藏导航栏

[英]Hide nav bar on scroll Function

如果 prevScrollPos > currentScrollPos。 这怎么可能是真的? 当 prevScrollPos 为 0 且 currentScrollPos 从不小于 0 时

var prevScrollPos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
  //Here
  if (prevScrollPos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-50px";
  }
  prevScrollpos = currentScrollPos;
}

prevScrollPos在你的函数结束时得到更新,所以当你向上滚动时, currentScrollPos将小于prevScrollPos

另外,你有一个错字:

prevScrollPos = currentScrollPos;

试试这个

function get_scroll() {
  if(window.scrollY > 30)
  {
    document.getElementById("navbar").style.top = "-50px";

  }else{
    document.getElementById("navbar").style.top = "0";
  }
}

document.getElementsByTagName("BODY")[0].setAttribute("onscroll","get_scroll()");

我在您的代码中添加了一些注释,这可能会消除您的疑问。

var prevScrollPos = window.pageYOffset;
// here if we assume the prevScrollPos as 0 then when the user scrolls the function gets executed.
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
  // Here, say currentScrollPos = 50px; so if condition fails and else block gets executed.
  if (prevScrollPos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-50px";
  }
  // since the prevScrollpos is being updated here, it will be greater than 0(will be 50px) next time.
  prevScrollpos = currentScrollPos;
}

当用户向上滚动时,该函数再次被调用,这次 if 条件满足,因为 50px(prevScrollPos) 将大于 0(当前假设他一直向上滚动)。

暂无
暂无

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

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