首页 > 解决方案 > 当用户向上滚动时,显示导航栏——但不是立即显示。如何?

问题描述

我想改进一个现有代码,允许我在用户向上滚动后显示导航栏,但延迟 XXX Px 向上滚动。如何将此像素量延迟集成到我的函数中?

我希望有人可以帮助我实现这一点。

/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */

var prevScrollpos = window.pageYOffset;

window.onscroll = function() {
    var currentScrollPos = window.pageYOffset;

    if (
        prevScrollpos > currentScrollPos
    ) {
        document.getElementById("navi").style.bottom = "0";

    } else {
        document.getElementById("navi").style.bottom = "-30vh";

    }
    prevScrollpos = currentScrollPos;
}

现在,导航栏在向上滚动时会立即出现。

标签: javascript

解决方案


试试这个,只需根据您需要多少像素来设置像素条件。

// When the user scrolls down 30px from the top of the document, slide down the navbar
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 30 || document.documentElement.scrollTop > 30) {
    document.getElementById("navbar").style.top = "0";
  } else {
   document.getElementById("navbar").style.top = "-50px";
 }
}

推荐阅读