HTML - 如何在滚动到页面上的某个点后使导航栏变得棒?

时间:2014-10-22 16:10:07

标签: html navbar

如何滚动到页面上的某个点后导航棒?我不希望它在滚过它之后立即粘住,而是在我到达页面上的另一个div时。

1 个答案:

答案 0 :(得分:4)

试试这个:

window.onscroll = function() {
  var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
  if (scrollTop >= document.getElementById("d").offsetTop) {
    document.getElementById("nav").style.position = "fixed";
    document.getElementById("d").style.marginTop = "50px";
    document.getElementById("nav").style.marginTop = "-50px";
  } else {
    document.getElementById("nav").style.position = "static";
    document.getElementById("d").style.marginTop = "0px";
    document.getElementById("nav").style.marginTop = "0px";
  }
}
nav {
  width: 100%;
  height: 50px;
  background: red;
  z-index: 100;
}
body {
  margin: 0;
  min-height: 1000px
}
#d {
  position: relative;
  top: 100px;
  width: 100%;
  height: 50px;
  background: yellow;
}
<body>
  <nav id="nav"></nav>
  <div id="d"></div>
</body>

当您滚动到黄色div时,红色导航栏会粘到视口的顶部并保持在那里,直到您向上滚动