Codepen:https://codepen.io/nickfindley/pen/dJqMQW
我希望获得与当前页面上相同的行为,除非在标题上没有设置高度。标题应该适合任何内容,根据窗口大小调整等进行调整。滚动时页面的其余部分也应该覆盖它。当导航栏通过一些JavaScript到达顶部时,它会粘在顶部。
var pn = $(".page-nav");
pns = "page-nav-scrolled";
hdr = $(".page-header").height();
$(window).scroll(function() {
if ($(this).scrollTop() > hdr) {
pn.addClass(pns);
} else {
pn.removeClass(pns);
}
});
$(window).on("scroll load", function() {
pn.toggleClass(pns, $(this).scrollTop() > hdr);
});

body {
margin: 0;
padding-top: 10em;
}
.page-header {
background-color: yellow;
text-align: center;
padding: 2em 0;
position: fixed;
top: 0;
width: 100%;
height: 20em;
z-index: -100;
}
.page-nav {
background-color: black;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.4);
width: 100%;
height: 4em;
position: relative;
margin-bottom: -4em;
z-index: 10000000;
}
.page-nav .nav-wrapper .nav-brand {
float: left;
padding: .584em 0;
font-size: 1.5em;
}
.page-nav .nav-wrapper .nav-brand a {
color: yellow;
}
.page-nav .nav-wrapper .nav-menu {
margin: 0;
float: right;
}
.page-nav .nav-wrapper .nav-menu .nav-item {
display: inline-block;
height: 4em;
line-height: 1em;
padding: 1.5em 0;
margin-left: 2em;
}
.page-nav .nav-wrapper .nav-menu .nav-item .nav-link {
color: yellow;
}
.page-nav-scrolled {
position: fixed;
width: 100%;
top: 0;
}
.page-main {
position: relative;
padding-top: 6em;
background-color: red;
}
.nav-wrapper, .page-content {
margin: 0 2em;
}
.header-content {
margin: 0 6em;
}
/* https://teamtreehouse.com/community/forum-tip-create-a-sticky-navigation-with-css-and-jquery-2 */

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="page-header" role="banner">
<section class="header-content">
<h1>Fixed Header</h1>
<p>Praesent non hendrerit sapien.
<p>Praesent non hendrerit sapien. Vivamus sit amet pellentesque nisl. Maecenas hendrerit elit ut mi porta, sagittis accumsan felis mollis. Fusce ut tincidunt lectus...</p>
</section>
</header>
<nav class="page-nav" role="navigation">
<div class="nav-wrapper">
<div class="nav-brand">
<a href="/">Brand</a>
</div>
<ul class="nav-menu">
<li class="nav-item nav-active">
<a class="nav-link" href="">News</a>
</li>
...
</ul>
</div>
</nav>
<main class="page-main">
<section class="page-content">
<article class="entry">
<header class="entry-header">
<h2>Quisque a dolor vel leo porttitor luctus</h2>
</header>
<section class="entry-content">
<p class="type">Lorem ipsum dolor sit amet...</p>
</section>
</article>
</section>
</main>
&#13;
会喜欢纯粹的CSS解决方案,但我对JS解决方案非常开放。
答案 0 :(得分:0)
请在此处查看codepen。我做的是
我相信这就是你想要的。
https://codepen.io/anon/pen/vpvmxo
只需发布已更改的css部分。
body {
margin: 0;
//padding-top: 10em;
}
.page-header {
background-color: yellow;
text-align: center;
padding: 2em 0;
position: relative;
top: 0;
width: 100%;
//height: 20em; // not really necessary, visible portion of header is determined by body padding-top
z-index: -100;
}