![](/img/trans.png)
[英]Navbar fixed bottom position and switch to static when scroll location reached
[英]change static navbar to fixed on scroll when bottom of hero section is reached
到达特定部分的结尾时,如何使静态定位的导航栏固定?
$(document).on("scroll", function() {
var navbar = $(".static-navbar");
navbar.addClass("fixed-navbar");
})
我试图使导航栏一到达“红色部分”就变得固定。
通过上面的jQuery代码,我成功在滚动事件触发后立即将其修复,但这不是我想要的。
编辑
我按照评论中的要求添加了slideDown功能...
而且看起来很棒!
关于此要说的两件事:
.slideDown()
用于设置隐藏元素的动画。 scroll
事件像AK47一样触发! slideUp()
,您必须等待动画的结尾以删除使其固定的类,然后确保它未被隐藏。 因此,您可以在slideUp()
回调中执行此操作。 我想您想要类似此片段的内容。
您只需使用.scrollTop()
与.fullscreen
height
值比较滚动了多少像素。
然后,很容易将导航栏设置为固定或静态。
// Navigation state "flag" var isFixed=false; $(document).on("scroll", function() { var navbar = $(".static-navbar"); var heroSectionHeight=$(".fullscreen").height(); // Set fixed if( $(window).scrollTop()>=heroSectionHeight && !isFixed ){ isFixed=true; navbar.hide().addClass("fixed-navbar").slideDown(600); } // Set static if( $(window).scrollTop()<heroSectionHeight && isFixed ){ isFixed=false; navbar.slideUp(600,function(){ navbar.removeClass("fixed-navbar").show(); }); } });
body { margin: 0; } .fullscreen { width: 100%; height: 100vh; background-color: #000; color: #fff; text-align: center; } .bg-red { background-color: red; } .static-navbar { width: 100%; position: static; padding: 25px 0; background-color: rgba(0, 0, 0, 1); border-bottom: 1px solid rgba(255, 255, 255, .15); } .fixed-navbar { position: fixed; background-color: rgba(255, 255, 255, 1); color: #000; border-bottom: 1px solid rgba(255, 255, 255, .15); }
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <div class="fullscreen"> <nav class="static-navbar"> Static Navbar </nav> <div style="padding-top: 280px;">HERO SECTION</div> </div> <div class="fullscreen bg-red" style="padding-top: 50px; padding-bottom: 50px;"> <div style="padding-top: 280px;">RED SECTION</div> </div>
最好在整页模式下查看此代码段
(否则,高度太小会闪烁)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.