如何在用户延迟停止滚动后移动导航栏 (JavaScript)

How to move navigation bar after user stops scrolling with delay (JavaScript)

我是 JavaScript 的新手,使用以下代码可以在用户滚动时隐藏导航栏。

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

function scrollFunction() {
  if (document.body.scroll > 40 || document.documentElement.scroll > 40) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "144px";
  }
}

我试图让导航栏在用户停止滚动后(短暂延迟后)消失,然后在用户再次开始滚动时再次显示。

我尝试了各种方法,包括使用 setInterval(function, delay) 循环函数 并使用 window.addEventListener 等待滚动,但似乎对我没有任何作用。

有人可以为我指出正确的设置方法吗?

非常感谢您的帮助, 埃利亚

您可以在处理滚动事件时使用setTimeout()在延迟后隐藏导航栏

window.onscroll = function() {scrollFunction()};

let hideTimer = 0;

function scrollFunction() {
  // show navbar whenever the user scroll
  document.getElementById("navbar").style.top = "144px";

  // clear the previously schduled hiding (if it exist)
  hideTimer && clearTimeout(hideTimer);

  // Schedule hiding (delaying)
  hideTimer = setTimeout(() => {
    document.getElementById("navbar").style.top = "0";
  }, 500); // delayed by 0.5 second
}

我还没有测试过,但它应该可以解决问题![​​=12=]