如果用户向下滚动页面,第一个 header 元素会消失
First header element disappears if user scrolls down the page
我开发了以下简单的 HMTL
和 CSS
代码,您也可以在 de JSFiddle
here:
中找到这些代码
body {
margin: 0;
}
.header {
width: 80%;
height: 10%;
margin-left: 10%;
position: fixed;
top: 0;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.sub_header_01 {
width: 100%;
height: 100%;
float: left;
text-align: center;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: blue;
}
.sub_header_02 {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
float: left;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.image {
width: 30%;
height: 100%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: green;
}
/* Navigation */
.navigation {
width: 70%;
height: 100%;
position: relative;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: aqua;
}
.navigation_button {
width: 20%;
height: 100%;
float: right;
cursor: pointer;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: fuchsia;
}
.bar1, .bar2, .bar3 {
width: 100%;
height: 20%;
margin: 4% 0;
background-color: #333;
}
/* Content */
.content {
width: 80%;
margin-top: 10%;
margin-left: 10%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: red;
}
<div class="header">
<div class="sub_header_01">
This is a webpage
</div>
<div class="sub_header_02">
<div class="image">
Image
</div>
<div class="navigation">
<div class="navigation_button">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</div>
</div>
</div>
<div class="content">
<p>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under. Breakfast procuring nay end happiness allowance assurance frankness. Met simplicity nor difficulty unreserved who. Entreaties mr conviction dissimilar me astonished estimating cultivated. On no applauded exquisite my additions. Pronounce add boy estimable nay suspected. You sudden nay elinor thirty esteem temper. Quiet leave shy you gay off asked large style. Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other. Received shutters expenses ye he pleasant. Drift as blind above at up. No up simple county stairs do should praise as. Drawings sir gay together landlord had law smallest. Formerly welcomed attended declared met say unlocked. Jennings outlived no dwelling denoting in peculiar as he believed. Behaviour excellent middleton be as it curiosity departure ourselves. On then sake home is am leaf. Of suspicion do departure at extremely he believing. Do know said mind do rent they oh hope of. General enquire picture letters garrets on offices of no on. Say one hearing between excited evening all inhabit thought you. Style begin mr heard by in music tried do. To unreserved projection no introduced invitation. Was justice improve age article between. No projection as up preference reasonably delightful celebrated. Preserved and abilities assurance tolerably breakfast use saw. And painted letters forming far village elderly compact. Her rest west each spot his and you knew. Estate gay wooded depart six far her. Of we be have it lose gate bred. Do separate removing or expenses in. Had covered but evident chapter matters anxious. Received overcame oh sensible so at an. Formed do change merely to county it. Am separate contempt domestic to to oh. On relation my so addition branched. Put hearing cottage she norland letters equally prepare too. Replied exposed savings he no viewing as up. Soon body add him hill. No father living really people estate if. Mistake do produce beloved demesne if am pursuit. Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society. Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye. Remain valley who mrs uneasy remove wooded him you. Her questions favourite him concealed. We to wife face took he. The taste begin early old why since dried can first. Prepared as or humoured formerly. Evil mrs true get post. Express village evening prudent my as ye hundred forming. Thoughts she why not directly reserved packages you. Winter an silent favour of am tended mutual. </p>
如您所见,我有一个由两个 sub-headers 组成的 header。 .sub-header_01
显示网站标题,.sub_header_02
在左侧提供一个 .image
,在右侧提供一个 .navigation
。
到目前为止一切正常。
现在,我的目标是让 .sub_header_01
在用户 向下滚动 内容后消失。 .sub_header_02
应保持在 .position: fixed
而 .sub_header_01
应该在页面 向下滚动 时消失。一旦用户向上滚动,.sub_header_01
应该再次出现。
你知道我需要在我的代码中更改什么才能使它工作吗?
(function(){
var position = 0;
// should start at 0
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if(scroll > position) {
$('.sub_header_01').hide();
} else {
$('.sub_header_01').show();
}
position = scroll;
});
})()
body {
margin: 0;
}
.header {
width: 80%;
height: 10%;
margin-left: 10%;
position: fixed;
top: 0;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.sub_header_01 {
width: 100%;
height: 100%;
float: left;
text-align: center;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: blue;
}
.sub_header_02 {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
float: left;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.image {
width: 30%;
height: 100%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: green;
}
/* Navigation */
.navigation {
width: 70%;
height: 100%;
position: relative;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: aqua;
}
.navigation_button {
width: 20%;
height: 100%;
float: right;
cursor: pointer;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: fuchsia;
}
.bar1, .bar2, .bar3 {
width: 100%;
height: 20%;
margin: 4% 0;
background-color: #333;
}
/* Content */
.content {
width: 80%;
margin-top: 10%;
margin-left: 10%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="header">
<div class="sub_header_01">
This is a webpage
</div>
<div class="sub_header_02">
<div class="image">
Image
</div>
<div class="navigation">
<div class="navigation_button">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</div>
</div>
</div>
<div class="content">
<p>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under. Breakfast procuring nay end happiness allowance assurance frankness. Met simplicity nor difficulty unreserved who. Entreaties mr conviction dissimilar me astonished estimating cultivated. On no applauded exquisite my additions. Pronounce add boy estimable nay suspected. You sudden nay elinor thirty esteem temper. Quiet leave shy you gay off asked large style. Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other. Received shutters expenses ye he pleasant. Drift as blind above at up. No up simple county stairs do should praise as. Drawings sir gay together landlord had law smallest. Formerly welcomed attended declared met say unlocked. Jennings outlived no dwelling denoting in peculiar as he believed. Behaviour excellent middleton be as it curiosity departure ourselves. On then sake home is am leaf. Of suspicion do departure at extremely he believing. Do know said mind do rent they oh hope of. General enquire picture letters garrets on offices of no on. Say one hearing between excited evening all inhabit thought you. Style begin mr heard by in music tried do. To unreserved projection no introduced invitation. Was justice improve age article between. No projection as up preference reasonably delightful celebrated. Preserved and abilities assurance tolerably breakfast use saw. And painted letters forming far village elderly compact. Her rest west each spot his and you knew. Estate gay wooded depart six far her. Of we be have it lose gate bred. Do separate removing or expenses in. Had covered but evident chapter matters anxious. Received overcame oh sensible so at an. Formed do change merely to county it. Am separate contempt domestic to to oh. On relation my so addition branched. Put hearing cottage she norland letters equally prepare too. Replied exposed savings he no viewing as up. Soon body add him hill. No father living really people estate if. Mistake do produce beloved demesne if am pursuit. Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society. Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye. Remain valley who mrs uneasy remove wooded him you. Her questions favourite him concealed. We to wife face took he. The taste begin early old why since dried can first. Prepared as or humoured formerly. Evil mrs true get post. Express village evening prudent my as ye hundred forming. Thoughts she why not directly reserved packages you. Winter an silent favour of am tended mutual. </p>
您可以将 position:sticky
与 .sub_header_02
一起使用,将 position:absolute
与 .sub_header_01
一起使用,然后删除 header 包装器:
body {
margin: 0;
}
.header {
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.sub_header_01 {
position:absolute;
top:0;
height: 10vh;
width:80%;
margin:auto;
left:0;
right:0;
text-align: center;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: blue;
}
.sub_header_02 {
height: 10vh;
width:80%;
margin:10vh auto 0;
position:sticky;
top:0;
display: flex;
justify-content: space-between;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.image {
width: 30%;
height: 100%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: green;
}
/* Navigation */
.navigation {
width: 70%;
height: 100%;
position: relative;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: aqua;
}
.navigation_button {
width: 20%;
height: 100%;
float: right;
cursor: pointer;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: fuchsia;
}
.bar1, .bar2, .bar3 {
width: 100%;
height: 20%;
margin: 4% 0;
background-color: #333;
}
/* Content */
.content {
width: 80%;
margin-left: 10%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: red;
}
<div class="sub_header_01">
This is a webpage
</div>
<div class="sub_header_02">
<div class="image">
Image
</div>
<div class="navigation">
<div class="navigation_button">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</div>
</div>
<div class="content">
<p>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under. Breakfast procuring nay end happiness allowance assurance frankness. Met simplicity nor difficulty unreserved who. Entreaties mr conviction dissimilar me astonished estimating cultivated. On no applauded exquisite my additions. Pronounce add boy estimable nay suspected. You sudden nay elinor thirty esteem temper. Quiet leave shy you gay off asked large style. Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other. Received shutters expenses ye he pleasant. Drift as blind above at up. No up simple county stairs do should praise as. Drawings sir gay together landlord had law smallest. Formerly welcomed attended declared met say unlocked. Jennings outlived no dwelling denoting in peculiar as he believed. Behaviour excellent middleton be as it curiosity departure ourselves. On then sake home is am leaf. Of suspicion do departure at extremely he believing. Do know said mind do rent they oh hope of. General enquire picture letters garrets on offices of no on. Say one hearing between excited evening all inhabit thought you. Style begin mr heard by in music tried do. To unreserved projection no introduced invitation. Was justice improve age article between. No projection as up preference reasonably delightful celebrated. Preserved and abilities assurance tolerably breakfast use saw. And painted letters forming far village elderly compact. Her rest west each spot his and you knew. Estate gay wooded depart six far her. Of we be have it lose gate bred. Do separate removing or expenses in. Had covered but evident chapter matters anxious. Received overcame oh sensible so at an. Formed do change merely to county it. Am separate contempt domestic to to oh. On relation my so addition branched. Put hearing cottage she norland letters equally prepare too. Replied exposed savings he no viewing as up. Soon body add him hill. No father living really people estate if. Mistake do produce beloved demesne if am pursuit. Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society. Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye. Remain valley who mrs uneasy remove wooded him you. Her questions favourite him concealed. We to wife face took he. The taste begin early old why since dried can first. Prepared as or humoured formerly. Evil mrs true get post. Express village evening prudent my as ye hundred forming. Thoughts she why not directly reserved packages you. Winter an silent favour of am tended mutual. </p>
我使用 Javascript 为您整理了一些内容。
它比使用纯 css 稍微复杂一点,但它允许您看到页眉,无论用户在页面下方多远,只需启动向上滚动即可。
// Shadow on Scroll
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 0) {
$('#HeadWrap').addClass('Active');
} else {
$('#HeadWrap').removeClass('Active');
}
didScroll = true;
});
// Hide header on scroll down
var didScroll,
lastScrollTop = 0,
trigger = 0,
navHeight = $('#HeadWrap').outerHeight();
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 0);
function hasScrolled() {
var st = $(this).scrollTop();
// Ensure scroll more than trigger
if (Math.abs(lastScrollTop - st) <= trigger)
return;
// If past .Head add .NavUp.
if (st > lastScrollTop && st > navHeight) {
// Scroll Down
$('#HeadWrap').removeClass('NavDown').addClass('NavUp');
} else {
// Scroll Up
if (st + $(window).height() < $(document).height()) {
$('#HeadWrap').removeClass('NavUp').addClass('NavDown');
}
}
lastScrollTop = st;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#HeadWrap {
position: fixed;
top: 0;
width: 100%;
background: #e5e5e5;
transition: all .2s ease-in-out;
z-index: 9999;
}
#HeadWrap.Active {
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}
#HeadWrap.NavUp {
top: -50px;
}
#Header {
position: relative;
height: 50px;
padding: 0 10px;
background: blue;
color: #fff;
z-index: 100;
}
#SubHdr {
background: #111;
color: #fff;
display: flex;
height: 30px;
white-space: nowrap;
justify-content: space-between;
}
#Logo {
background: green;
width:100px;
}
nav{
display: flex;
flex:1;
}
nav a{
display: flex;
flex:1;
justify-content:center;
align-items:center;
color:#fff;
}
main {
position: relative;
padding-top: 90px;
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="HeadWrap">
<header id="Header" class="MxW">
HEADER
</header>
<section id="SubHdr">
<div id="Logo">
LOGO
</div>
<nav>
<a href="#">LINK 1</a>
<a href="#">LINK 2</a>
<a href="#">LINK 3</a>
<a href="#">LINK 4</a>
<a href="#">LINK 5</a>
</nav>
</section>
</div>
<main>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut cursus tellus vitae lacus vestibulum, a consequat metus mattis. Cras viverra mollis finibus. Curabitur maximus purus leo, vitae pellentesque elit consequat at. Sed vestibulum purus fringilla ligula egestas aliquam. Morbi ac euismod neque. Duis egestas magna arcu, vitae porta leo mattis at. Donec non ante ligula. Morbi nec maximus libero. Curabitur euismod efficitur lorem at dignissim. Nulla imperdiet mi a est viverra congue.</p>
<p>Sed sit amet ornare enim. Sed vestibulum est id ligula auctor lobortis. Vivamus facilisis ligula sed risus laoreet aliquam. Vestibulum cursus accumsan fringilla. Donec consequat massa quis justo tempor malesuada. Quisque elementum viverra lorem, sed vestibulum ipsum efficitur eu. Pellentesque sagittis condimentum justo, eu tristique ante imperdiet et.</p>
<p>Integer mauris ipsum, dictum sit amet nulla eget, fermentum rhoncus nulla. Mauris id magna mattis, imperdiet est vel, laoreet nisi. Morbi blandit arcu et porttitor condimentum. Morbi lobortis, quam vitae pretium vehicula, nisl magna sagittis nisi, ac pellentesque ligula erat a nunc. Aenean interdum tempus ante in sollicitudin. Aliquam vitae vehicula ligula, bibendum blandit arcu. Integer euismod ullamcorper neque in posuere. Proin sit amet quam neque. Sed bibendum neque ipsum, ut sodales ante aliquet eu. Maecenas ante elit, rutrum eu suscipit at, fringilla eget justo. Cras eu vehicula sapien. Aenean ullamcorper, eros in fermentum tristique, nulla urna lobortis velit, sed semper libero arcu sit amet risus. Nulla luctus imperdiet leo at laoreet. Vivamus luctus ultrices nisi, non sodales mi gravida malesuada.</p>
In hac habitasse platea dictumst. Duis mi nulla, blandit id augue non, imperdiet laoreet odio. Nunc tempor lectus vel tincidunt rutrum. Praesent vel laoreet arcu. Aenean a tincidunt urna. Suspendisse rutrum tempus sem ut egestas. Nam malesuada tellus nibh, eget convallis dolor egestas in. Donec nec accumsan quam. Pellentesque ultrices, ex vel feugiat finibus, ex dui imperdiet elit, eget ultrices sapien tortor dictum lectus. Aliquam sapien metus, faucibus ut elementum euismod, pulvinar sed velit. Ut facilisis fermentum nunc, a sagittis nulla tincidunt in. Ut volutpat facilisis nunc. Aenean nisl nisl, congue nec scelerisque in, euismod vitae libero. Mauris vehicula porta mattis.
</main>
我开发了以下简单的 HMTL
和 CSS
代码,您也可以在 de JSFiddle
here:
body {
margin: 0;
}
.header {
width: 80%;
height: 10%;
margin-left: 10%;
position: fixed;
top: 0;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.sub_header_01 {
width: 100%;
height: 100%;
float: left;
text-align: center;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: blue;
}
.sub_header_02 {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
float: left;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.image {
width: 30%;
height: 100%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: green;
}
/* Navigation */
.navigation {
width: 70%;
height: 100%;
position: relative;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: aqua;
}
.navigation_button {
width: 20%;
height: 100%;
float: right;
cursor: pointer;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: fuchsia;
}
.bar1, .bar2, .bar3 {
width: 100%;
height: 20%;
margin: 4% 0;
background-color: #333;
}
/* Content */
.content {
width: 80%;
margin-top: 10%;
margin-left: 10%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: red;
}
<div class="header">
<div class="sub_header_01">
This is a webpage
</div>
<div class="sub_header_02">
<div class="image">
Image
</div>
<div class="navigation">
<div class="navigation_button">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</div>
</div>
</div>
<div class="content">
<p>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under. Breakfast procuring nay end happiness allowance assurance frankness. Met simplicity nor difficulty unreserved who. Entreaties mr conviction dissimilar me astonished estimating cultivated. On no applauded exquisite my additions. Pronounce add boy estimable nay suspected. You sudden nay elinor thirty esteem temper. Quiet leave shy you gay off asked large style. Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other. Received shutters expenses ye he pleasant. Drift as blind above at up. No up simple county stairs do should praise as. Drawings sir gay together landlord had law smallest. Formerly welcomed attended declared met say unlocked. Jennings outlived no dwelling denoting in peculiar as he believed. Behaviour excellent middleton be as it curiosity departure ourselves. On then sake home is am leaf. Of suspicion do departure at extremely he believing. Do know said mind do rent they oh hope of. General enquire picture letters garrets on offices of no on. Say one hearing between excited evening all inhabit thought you. Style begin mr heard by in music tried do. To unreserved projection no introduced invitation. Was justice improve age article between. No projection as up preference reasonably delightful celebrated. Preserved and abilities assurance tolerably breakfast use saw. And painted letters forming far village elderly compact. Her rest west each spot his and you knew. Estate gay wooded depart six far her. Of we be have it lose gate bred. Do separate removing or expenses in. Had covered but evident chapter matters anxious. Received overcame oh sensible so at an. Formed do change merely to county it. Am separate contempt domestic to to oh. On relation my so addition branched. Put hearing cottage she norland letters equally prepare too. Replied exposed savings he no viewing as up. Soon body add him hill. No father living really people estate if. Mistake do produce beloved demesne if am pursuit. Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society. Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye. Remain valley who mrs uneasy remove wooded him you. Her questions favourite him concealed. We to wife face took he. The taste begin early old why since dried can first. Prepared as or humoured formerly. Evil mrs true get post. Express village evening prudent my as ye hundred forming. Thoughts she why not directly reserved packages you. Winter an silent favour of am tended mutual. </p>
如您所见,我有一个由两个 sub-headers 组成的 header。 .sub-header_01
显示网站标题,.sub_header_02
在左侧提供一个 .image
,在右侧提供一个 .navigation
。
到目前为止一切正常。
现在,我的目标是让 .sub_header_01
在用户 向下滚动 内容后消失。 .sub_header_02
应保持在 .position: fixed
而 .sub_header_01
应该在页面 向下滚动 时消失。一旦用户向上滚动,.sub_header_01
应该再次出现。
你知道我需要在我的代码中更改什么才能使它工作吗?
(function(){
var position = 0;
// should start at 0
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if(scroll > position) {
$('.sub_header_01').hide();
} else {
$('.sub_header_01').show();
}
position = scroll;
});
})()
body {
margin: 0;
}
.header {
width: 80%;
height: 10%;
margin-left: 10%;
position: fixed;
top: 0;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.sub_header_01 {
width: 100%;
height: 100%;
float: left;
text-align: center;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: blue;
}
.sub_header_02 {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
float: left;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.image {
width: 30%;
height: 100%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: green;
}
/* Navigation */
.navigation {
width: 70%;
height: 100%;
position: relative;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: aqua;
}
.navigation_button {
width: 20%;
height: 100%;
float: right;
cursor: pointer;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: fuchsia;
}
.bar1, .bar2, .bar3 {
width: 100%;
height: 20%;
margin: 4% 0;
background-color: #333;
}
/* Content */
.content {
width: 80%;
margin-top: 10%;
margin-left: 10%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="header">
<div class="sub_header_01">
This is a webpage
</div>
<div class="sub_header_02">
<div class="image">
Image
</div>
<div class="navigation">
<div class="navigation_button">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</div>
</div>
</div>
<div class="content">
<p>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under. Breakfast procuring nay end happiness allowance assurance frankness. Met simplicity nor difficulty unreserved who. Entreaties mr conviction dissimilar me astonished estimating cultivated. On no applauded exquisite my additions. Pronounce add boy estimable nay suspected. You sudden nay elinor thirty esteem temper. Quiet leave shy you gay off asked large style. Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other. Received shutters expenses ye he pleasant. Drift as blind above at up. No up simple county stairs do should praise as. Drawings sir gay together landlord had law smallest. Formerly welcomed attended declared met say unlocked. Jennings outlived no dwelling denoting in peculiar as he believed. Behaviour excellent middleton be as it curiosity departure ourselves. On then sake home is am leaf. Of suspicion do departure at extremely he believing. Do know said mind do rent they oh hope of. General enquire picture letters garrets on offices of no on. Say one hearing between excited evening all inhabit thought you. Style begin mr heard by in music tried do. To unreserved projection no introduced invitation. Was justice improve age article between. No projection as up preference reasonably delightful celebrated. Preserved and abilities assurance tolerably breakfast use saw. And painted letters forming far village elderly compact. Her rest west each spot his and you knew. Estate gay wooded depart six far her. Of we be have it lose gate bred. Do separate removing or expenses in. Had covered but evident chapter matters anxious. Received overcame oh sensible so at an. Formed do change merely to county it. Am separate contempt domestic to to oh. On relation my so addition branched. Put hearing cottage she norland letters equally prepare too. Replied exposed savings he no viewing as up. Soon body add him hill. No father living really people estate if. Mistake do produce beloved demesne if am pursuit. Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society. Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye. Remain valley who mrs uneasy remove wooded him you. Her questions favourite him concealed. We to wife face took he. The taste begin early old why since dried can first. Prepared as or humoured formerly. Evil mrs true get post. Express village evening prudent my as ye hundred forming. Thoughts she why not directly reserved packages you. Winter an silent favour of am tended mutual. </p>
您可以将 position:sticky
与 .sub_header_02
一起使用,将 position:absolute
与 .sub_header_01
一起使用,然后删除 header 包装器:
body {
margin: 0;
}
.header {
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.sub_header_01 {
position:absolute;
top:0;
height: 10vh;
width:80%;
margin:auto;
left:0;
right:0;
text-align: center;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: blue;
}
.sub_header_02 {
height: 10vh;
width:80%;
margin:10vh auto 0;
position:sticky;
top:0;
display: flex;
justify-content: space-between;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: yellow;
}
.image {
width: 30%;
height: 100%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: green;
}
/* Navigation */
.navigation {
width: 70%;
height: 100%;
position: relative;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: aqua;
}
.navigation_button {
width: 20%;
height: 100%;
float: right;
cursor: pointer;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: fuchsia;
}
.bar1, .bar2, .bar3 {
width: 100%;
height: 20%;
margin: 4% 0;
background-color: #333;
}
/* Content */
.content {
width: 80%;
margin-left: 10%;
box-sizing: border-box;
border-style: solid;
border-width: 1px;
background-color: red;
}
<div class="sub_header_01">
This is a webpage
</div>
<div class="sub_header_02">
<div class="image">
Image
</div>
<div class="navigation">
<div class="navigation_button">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</div>
</div>
<div class="content">
<p>Am no an listening depending up believing. Enough around remove to barton agreed regret in or it. Advantage mr estimable be commanded provision. Year well shot deny shew come now had. Shall downs stand marry taken his for out. Do related mr account brandon an up. Wrong for never ready ham these witty him. Our compass see age uncivil matters weather forbade her minutes. Ready how but truth son new under. Breakfast procuring nay end happiness allowance assurance frankness. Met simplicity nor difficulty unreserved who. Entreaties mr conviction dissimilar me astonished estimating cultivated. On no applauded exquisite my additions. Pronounce add boy estimable nay suspected. You sudden nay elinor thirty esteem temper. Quiet leave shy you gay off asked large style. Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other. Received shutters expenses ye he pleasant. Drift as blind above at up. No up simple county stairs do should praise as. Drawings sir gay together landlord had law smallest. Formerly welcomed attended declared met say unlocked. Jennings outlived no dwelling denoting in peculiar as he believed. Behaviour excellent middleton be as it curiosity departure ourselves. On then sake home is am leaf. Of suspicion do departure at extremely he believing. Do know said mind do rent they oh hope of. General enquire picture letters garrets on offices of no on. Say one hearing between excited evening all inhabit thought you. Style begin mr heard by in music tried do. To unreserved projection no introduced invitation. Was justice improve age article between. No projection as up preference reasonably delightful celebrated. Preserved and abilities assurance tolerably breakfast use saw. And painted letters forming far village elderly compact. Her rest west each spot his and you knew. Estate gay wooded depart six far her. Of we be have it lose gate bred. Do separate removing or expenses in. Had covered but evident chapter matters anxious. Received overcame oh sensible so at an. Formed do change merely to county it. Am separate contempt domestic to to oh. On relation my so addition branched. Put hearing cottage she norland letters equally prepare too. Replied exposed savings he no viewing as up. Soon body add him hill. No father living really people estate if. Mistake do produce beloved demesne if am pursuit. Cause dried no solid no an small so still widen. Ten weather evident smiling bed against she examine its. Rendered far opinions two yet moderate sex striking. Sufficient motionless compliment by stimulated assistance at. Convinced resolving extensive agreeable in it on as remainder. Cordially say affection met who propriety him. Are man she towards private weather pleased. In more part he lose need so want rank no. At bringing or he sensible pleasure. Prevent he parlors do waiting be females an message society. Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye. Remain valley who mrs uneasy remove wooded him you. Her questions favourite him concealed. We to wife face took he. The taste begin early old why since dried can first. Prepared as or humoured formerly. Evil mrs true get post. Express village evening prudent my as ye hundred forming. Thoughts she why not directly reserved packages you. Winter an silent favour of am tended mutual. </p>
我使用 Javascript 为您整理了一些内容。
它比使用纯 css 稍微复杂一点,但它允许您看到页眉,无论用户在页面下方多远,只需启动向上滚动即可。
// Shadow on Scroll
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > 0) {
$('#HeadWrap').addClass('Active');
} else {
$('#HeadWrap').removeClass('Active');
}
didScroll = true;
});
// Hide header on scroll down
var didScroll,
lastScrollTop = 0,
trigger = 0,
navHeight = $('#HeadWrap').outerHeight();
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 0);
function hasScrolled() {
var st = $(this).scrollTop();
// Ensure scroll more than trigger
if (Math.abs(lastScrollTop - st) <= trigger)
return;
// If past .Head add .NavUp.
if (st > lastScrollTop && st > navHeight) {
// Scroll Down
$('#HeadWrap').removeClass('NavDown').addClass('NavUp');
} else {
// Scroll Up
if (st + $(window).height() < $(document).height()) {
$('#HeadWrap').removeClass('NavUp').addClass('NavDown');
}
}
lastScrollTop = st;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#HeadWrap {
position: fixed;
top: 0;
width: 100%;
background: #e5e5e5;
transition: all .2s ease-in-out;
z-index: 9999;
}
#HeadWrap.Active {
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}
#HeadWrap.NavUp {
top: -50px;
}
#Header {
position: relative;
height: 50px;
padding: 0 10px;
background: blue;
color: #fff;
z-index: 100;
}
#SubHdr {
background: #111;
color: #fff;
display: flex;
height: 30px;
white-space: nowrap;
justify-content: space-between;
}
#Logo {
background: green;
width:100px;
}
nav{
display: flex;
flex:1;
}
nav a{
display: flex;
flex:1;
justify-content:center;
align-items:center;
color:#fff;
}
main {
position: relative;
padding-top: 90px;
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="HeadWrap">
<header id="Header" class="MxW">
HEADER
</header>
<section id="SubHdr">
<div id="Logo">
LOGO
</div>
<nav>
<a href="#">LINK 1</a>
<a href="#">LINK 2</a>
<a href="#">LINK 3</a>
<a href="#">LINK 4</a>
<a href="#">LINK 5</a>
</nav>
</section>
</div>
<main>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut cursus tellus vitae lacus vestibulum, a consequat metus mattis. Cras viverra mollis finibus. Curabitur maximus purus leo, vitae pellentesque elit consequat at. Sed vestibulum purus fringilla ligula egestas aliquam. Morbi ac euismod neque. Duis egestas magna arcu, vitae porta leo mattis at. Donec non ante ligula. Morbi nec maximus libero. Curabitur euismod efficitur lorem at dignissim. Nulla imperdiet mi a est viverra congue.</p>
<p>Sed sit amet ornare enim. Sed vestibulum est id ligula auctor lobortis. Vivamus facilisis ligula sed risus laoreet aliquam. Vestibulum cursus accumsan fringilla. Donec consequat massa quis justo tempor malesuada. Quisque elementum viverra lorem, sed vestibulum ipsum efficitur eu. Pellentesque sagittis condimentum justo, eu tristique ante imperdiet et.</p>
<p>Integer mauris ipsum, dictum sit amet nulla eget, fermentum rhoncus nulla. Mauris id magna mattis, imperdiet est vel, laoreet nisi. Morbi blandit arcu et porttitor condimentum. Morbi lobortis, quam vitae pretium vehicula, nisl magna sagittis nisi, ac pellentesque ligula erat a nunc. Aenean interdum tempus ante in sollicitudin. Aliquam vitae vehicula ligula, bibendum blandit arcu. Integer euismod ullamcorper neque in posuere. Proin sit amet quam neque. Sed bibendum neque ipsum, ut sodales ante aliquet eu. Maecenas ante elit, rutrum eu suscipit at, fringilla eget justo. Cras eu vehicula sapien. Aenean ullamcorper, eros in fermentum tristique, nulla urna lobortis velit, sed semper libero arcu sit amet risus. Nulla luctus imperdiet leo at laoreet. Vivamus luctus ultrices nisi, non sodales mi gravida malesuada.</p>
In hac habitasse platea dictumst. Duis mi nulla, blandit id augue non, imperdiet laoreet odio. Nunc tempor lectus vel tincidunt rutrum. Praesent vel laoreet arcu. Aenean a tincidunt urna. Suspendisse rutrum tempus sem ut egestas. Nam malesuada tellus nibh, eget convallis dolor egestas in. Donec nec accumsan quam. Pellentesque ultrices, ex vel feugiat finibus, ex dui imperdiet elit, eget ultrices sapien tortor dictum lectus. Aliquam sapien metus, faucibus ut elementum euismod, pulvinar sed velit. Ut facilisis fermentum nunc, a sagittis nulla tincidunt in. Ut volutpat facilisis nunc. Aenean nisl nisl, congue nec scelerisque in, euismod vitae libero. Mauris vehicula porta mattis.
</main>