当收割台消失时,固定位置的导航栏保持在顶部

Navbar with fixed position staying on the top while header disappear

本文关键字:导航 顶部 位置 定位 收割 消失      更新时间:2023-09-26

我想制作固定位置的导航栏。在页面顶部,导航条应位于页眉下方,向下滚动后,当页眉不再可见时,导航条应该位于页面顶部。我该怎么做?当我在导航栏和页面顶部之间向下滚动后尝试这样做时,仍然是标题的高度(即使它不再可见)。

这是我的css:

header{
  background-color: red;
  width: 100%;
  height: 100px;
}
nav{
  position: fixed;
    float:left;
  height: 100px;
  width: 100px;
    margin-left: 10px;
    margin-right: 50px;
    margin-top:50px;
    background-color: green;  
}
main{
background-color: blue;
height: 1500px;
margin-left:15%;
margin-right:5%;
margin-top:50px;
}

和jfiddle:https://jsfiddle.net/pg2kwk5e/

您可以在滚动一定量后使用javascript向nav元素添加一个类。

我使用了Jquery,因为它可以更快、更容易地在实际操作中显示这一点。

示例

我只是在窗口滚动超过150个像素后,在nav中添加一个类.fixedTop,该类本身只有top:0;margin0;,可以将绝对定位的元素移动到顶部,并删除之前设置的边距。

代码:

var $nav = $("nav"),

$(window).scroll(function() {
  if($(this).scrollTop() > 150) {
     $nav.addClass('fixedTop');
  } else {
     $nav.removeClass('fixedTop');
  }
})

CSS:

.fixedTop {
  top: 0;
  margin: 0 !important;
}