header 前面的导航栏,滚动时始终位于屏幕顶部

Navigation bar in front of the header and always on top of the screen when scrolling

我正在尝试创建一个网站,加载后导航栏位于 header 下方,向下滚动时 - 导航栏应转到屏幕顶部并附加到它, 导航栏下的所有内容都应该在它后面。我希望它看起来像 http://www.w3schools.com/css/default.asp 适合计算机屏幕的网站。

我的示例(无法正常工作):[审查]

CSS代码:

* {
  box-sizing: border-box;
}
body {
  margin: 0;
  padding: 0;
}
.header {
  width: 100%;
  height: 100px;
  padding: 15px;
  color: #2A5282;
  background-color: #E8FF79;
  position: fixed;
  top: 0;
  z-index: -1;
}
.nav {
  width: 100%;
  height: 40px;
  color: white;
  background: #2A5282;
  position: absolute; 
  top: 100px;
  z-index: 1;
}
.nav ul {
  margin: 0;
  padding: 0;
  overflow: hidden;
}
.nav ul li {
  list-style-type: none;
  float: left;
}
.nav ul li a {
  color: #E8FF79;
  text-align: center;
  text-decoration: none;
  font: bold 16px verdana;
  width: 150px;
  margin: 0;
  padding: 10px 0;
  display: block;
}
.nav ul li a:hover {
  background-color: #2B5D9C;
}
.content {
  width: 100%;
  padding: 0 20px;
  color: black;
  background-color: white;
  font: bold 14px verdana;
  position: absolute;
  top: 140px;
  z-index: 1;
}

HTML代码:

<div class="header">
  <h1>This is a header</h1>
</div>
<div class="nav">
  <ul>
    <li><a href="#">Option 1</a></li>
    <li><a href="#">Option 2</a></li>
    <li><a href="#">Option 3</a></li>
    <li><a href="#">Option 4</a></li>
  </ul>
</div>
<div class="content">
  <p>This is a paragraph.</p>
  <p>This is a paragraph.</p>
  <p>This is a paragraph.</p>
  <p>This is a paragraph.</p>
  <p>This is a paragraph.</p>
  <!-->...<-->
</div>

我试图了解 w3schools 网站的源代码,但我缺少某些东西而且我不知道它是什么。我不想使用 Bootstrap。最好的解决方案是仅使用 HTML 和 CSS.

在你的项目上添加js

$(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() > 20) {
            $('.nav').addClass('nav-pin').fadeIn();
        } else {
            $('.nav').removeClass('nav-pin');
        }
    });
});

和css低于

.nav-pin{position:fixed; top:0; left:0; z-index:9999;}

将您的代码与评论中提供的 JSFiddle Rahul S 合并, this is the final code

另请注意,我从您的 css 的 .content class 中删除了 z-index 属性。

您可以这样做,请参见下面的示例:

<div id="scroller">Some controls</div>

CSS:

body {
    height: 3000px;
    top: 0;
    position: relative;
}
#scroller {
    position: relative;
    top: 100px;
    width: 100%;
    background: #CCC;
    height: 100px;
}

我们可以像这样使用 javascript 滚动大小写:

$(window).scroll(function () {
    if ($(window).scrollTop() > 100) {
        $('#scroller').css('top', $(window).scrollTop());
    }
}
);

有关详细信息,请参阅:http://jsfiddle.net/cc48t/