[英]Navigation bar in front of the header and always on top of the screen when scrolling
我正在嘗試創建一個網站,加載后,導航欄位於標題下方,向下滾動時-導航欄應轉到屏幕頂部並連接到它,以及導航欄下方的所有內容應該在它后面。 我希望它看起來像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。
您可以這樣做,請參見以下示例:
<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/
在您的項目上添加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合並, 這是最終代碼
另請注意,我從css的.content
類中刪除了z-index
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.