[英]How to stick a div/navigation bar to the top of the window when scrolled past it
I have a menu navbar that is right after a header 我有一个标题栏后面的菜单导航栏
<header>
<center>
<img src=""> Some other stuff
</center>
</header>
<div class="navbar">
<div class="nav">
<ul class="meniunav">
<li><a href=""><img src="home.svg" class="navicon"> Home</a></li>
<li><a href=""><img src="info.svg" class="navicon"> Info</a></li>
<li><a href=""><img src="contact.svg" class="navicon"> Contact</a></li>
</ul>
</div>
</div>
The header has 150px height and I want to make the navbar element stick to the top of the page if it gets there. 标头的高度为150px,如果要到达该页面,我想使navbar元素停留在页面顶部。 To be more clear: when I scroll down I want that element to get fixed at the top when it reaches it and if I scroll back up and it reaches the initial position to remove the fixed position.
更清楚地说:当我向下滚动时,我希望该元素到达顶部时固定在顶部,如果我向上滚动并到达初始位置以移除该固定位置。 How can I do this?
我怎样才能做到这一点?
you have two ways to do it: 您有两种方法可以做到:
First: use position: sticky;
第一:使用
position: sticky;
which works only on firefox (we will have to wait lot of time for this to come in standard) 只能在Firefox上使用(我们必须等待很多时间才能实现此标准)
Second (working on every browser): javascript. 第二(适用于所有浏览器):javascript。 There are many scripts on the internet, and you can easily find them.
互联网上有很多脚本,您可以轻松找到它们。 just type "Sticky Navigation" in Google.
只需在Google中输入“粘性导航”即可。 Here is example of it: https://codepen.io/Guilh/pen/JLKbn
这是它的示例: https : //codepen.io/Guilh/pen/JLKbn
Ok so apparently the simplest method is: 好的,显然最简单的方法是:
$(window).scroll(function() {
if($(this).scrollTop() >= 150) {
$(".navbar").addClass("sticky");
}
else {
$(".navbar").removeClass("sticky");
}
});
With the sticky class containing: 粘性类包含:
.sticky {
position: fixed;
top: 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.