javascript - How to stick a static header when scrolling
问题描述
I am trying to make my header/navbar fixed when you scroll down to the content. My header is static, I tried to change its value to fixed at the beginning, but if I do that, it disappears immediately.
I wanted to implement the example of W3School, but it didnt work and I dont know why. I also kept reading all the tutorials and Questions, but mostly they could solve it but changing the position to fixed.
window.onscroll = function() {
myFunction()
};
var header = document.getElementById("myHeader");
var sticky = header.offsetTop;
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
.navbar {
background-color: #AA0000;
width: 100vw;
position: static;
}
.logo a {
font-family: 'Lobster';
font-size: 40px;
float: left;
text-decoration: none;
color: white;
padding: 20px 35px;
}
.navcontent {
margin-left: 30%;
display: flex;
}
.navcontent a {}
.navcontent a::after {}
.navcontent a:hover::after {}
.dropdown-content {}
.dropdown:hover .dropdown-content {}
label {
margin: 0 auto;
font-size: 26px;
line-height: 70px;
display: none;
position: static;
}
#toggle {
display: none;
}
.sticky {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
HTML FIlE
<body>
<section class="navbar" id="myHeader">
<div class="logo">
<a href="index.html">Test</a>
</div>
<label for="toggle" style="color: white;">☰</label>
<input type="checkbox" id="toggle" />
<div class="navcontent">
<p><a href="index.html">Start</a></p>
<p><a href="puravida.html">Pura Vida</a></p>
<div class="dropdown">
<p><a href="reisen.html">Reisen</a></p>
<div class="dropdown-content">
<p><a href="blog/reiseinfos.html">Frag mich</a></p>
<p><a href="reiseberichte.html">Reiseblog</a></p>
</div>
</div>
<p><a href="aboutme.html">Über mich</a></p>
<p><a href="contact.html">Kontakt</a></p>
</div>
</section>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</body>
I hoped that the the W3School example could work because to my mind I just needed to implement the JS File and the .sticky class, but at the end I dont see any reaction/change
解决方案
You can use the z-index property to show it above.
.navbar{
position: fixed;
top: 0;
left: 0;
background-color: #AA0000;
width: 100vw;
z-index: 99;
}
推荐阅读
- powerbi - Power BI 切片器自定义
- jenkins - 在 Jenkins 作业中设置 ansible.cfg
- angular - 来自 Observable 的数组返回未定义
- ubuntu - kubectl 的每个命令的错误消息
- c# - 如何计算自定义属性并将其添加到从 OData API 检索的结果中?
- php - 在 Emacs 中以 Org 模式突出显示的 PHP 代码不起作用
- jquery - 如何在 Owl Carousel 2 中显示活动项目及其旁边的其余项目
- c - GCC 与 C11 标准中的位域类型
- onesignal - 我将 OneSignal 添加到网站中,然后运行 Google PageSpped Insights,如何解决此错误
- javascript - 在创建 CSS 自动收报机时防止在边上留出间距