Javascript 粘性菜单有效。索塔

Javascript 粘性菜单有效。索塔,javascript,html,css,menu,sticky,Javascript,Html,Css,Menu,Sticky,我正在尝试使用“粘性”水平菜单解决问题 它在技术上是有效的,因为当页面上下滚动时,菜单的位置是固定的 现在的问题是,然后页面被卷回原始位置,粘性菜单下对象的新静止位置返回到浏览器顶部。如果这有道理的话 下面是正在使用的javascript: <script> // When the user scrolls the page, execute myFunction window.onscroll = function() {myFunction()}; // Get

我正在尝试使用“粘性”水平菜单解决问题

它在技术上是有效的,因为当页面上下滚动时,菜单的位置是固定的

现在的问题是,然后页面被卷回原始位置,粘性菜单下对象的新静止位置返回到浏览器顶部。如果这有道理的话

下面是正在使用的javascript:

    <script>
  // When the user scrolls the page, execute myFunction 
window.onscroll = function() {myFunction()};

// Get the navbar
var navbar = document.getElementById("navbar_cont");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
</script>

任何帮助都将不胜感激。谢谢

为什么不一直给导航条定位:固定?为什么只在向下滚动时才将其修复?您可以添加一些HTML代码,或者将代码示例转换为可执行代码段,或者提供指向JSFIDLE的链接吗?您好,@PatrickHund。我感谢你的答复。我实际上继承了这个解决方案,我不是最有经验的javascript用户。但是,我看过使用相同开/关逻辑的在线教程。因此,这看起来确实像是标准方法。但是,对于一个粘性菜单,很难找到一个好的工作解决方案。大多数似乎是基于jquery的。
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky + #call-to-action  {
  padding-top:164px;
}