0

让我看看能不能解释一下。我想要一个导航栏的固定位置 top:100vh,所以当我向下滚动并输入我的下一个 div 时,导航栏棒在顶部,而不是卡在 position:fixed top:0 的开头。我想把它贴在顶部 100vh - 110vh 的位置。

这是一个油漆图像,可以更好地解释。据说我只能看到 100vh,所以当我滚动时,我会转到 100vh - 200vh .. 等等

我的绝妙图

除此之外,当我在页面的某个部分时,我希望在导航栏上有活动类。前任。如果我悬停在“关于”部分,我希望导航栏的“关于”链接具有“活动”类。

我希望你能理解我,我说的很清楚。对不起,如果我很困惑。

提前致谢。

4

2 回答 2

1

在页面上添加滚动事件

position :static 并在页面滚动顶部 < 100vh = 时 设置导航栏样式 window.innerHeight

然后检查页面滚动顶部是否> 100vh

将您的导航设置为top :0position : fixed

为显示动画添加类动画

window.onscroll = () => {
  let c = window.scrollY;

  if (c > window.innerHeight) {
    document.getElementById("nav").className = "fixed-nav";
  } else {
    document.getElementById("nav").className = "";
  }
}
div {
  background-color: blue;
}

nav {
  background-color: red;
}

.fixed-nav {
  position: fixed;
  width: 100%;
  top: 0;
}
<div style="height:100vh"></div>
<nav id="nav" style="height:100px"></nav>
<div style="height:100vh"></div>
<div style="height:100vh"></div>

于 2018-10-19T05:52:26.907 回答
1

基本上,您希望位于页面底部的导航栏已设置为position: absolute;top: 100vh;这意味着它会停留在那里并在您滚动时更改其位置。

一旦超出预期的滚动位置,您希望它粘在顶部。所以把这个位置设置为position: fixed;andtop: 0;让它粘在顶部。

此外,仅仅因为代码片段有效,不要复制粘贴代码,尝试了解这里实际发生的情况。

window.addEventListener('scroll', function(){
  if(window.scrollY > window.innerHeight){
    document.getElementById('navbar').classList.add("sticky");
  } else {
    document.getElementById('navbar').classList.remove("sticky");
  }
});
* {
  margin: 0;
  padding: 0;
}
.pageOne {
  min-height: 100vh;
  background: pink;
}

#navbar {
  height: 100px;
  position: absolute;
  width: 100%;
  top: 100vh;
  left: 0;
  background: lightgreen;
  z-index: 2;
}

#navbar.sticky {
  position: fixed;
  top: 0;
}

.pageTwo {
  min-height: 100vh;
  background: orange;
}

.pageThree {
  min-height: 100vh;
  background: purple;
}
<div class="pageOne">Div One</div>
<div id="navbar">Navbar</div>
<div class="pageTwo">Div Two</div>
<div class="pageThree">Div Three</div>
<div class="pageTwo">Div Two</div>
<div class="pageThree">Div Three</div>

于 2018-10-19T06:15:49.687 回答