当到达英雄部分的底部时,将静态导航栏更改为固定在滚动上

当达到特定部分的结尾时,如何使静态定位导航栏固定?

小提琴

$(document).on("scroll", function() { var navbar = $(".static-navbar"); navbar.addClass("fixed-navbar"); }) 

我试图让导航栏在达到“红色部分”后立即固定。
使用上面的这个jQuery代码,我设法在滚动事件被触发后立即修复它,但这不是我正在寻找的。

编辑

我添加了slideDownfunction,如评论中所述…
它看起来很棒!

关于此添加有两点要说:

  1. .slideDown()用于为隐藏元素设置动画。
    所以在你的情况下,你必须先隐藏它。
  2. 然后,需要一个“标志”来避免它被动画太多次……
    scroll事件像AK47一样发射!
    ;)
  3. 关于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() 
 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); } 
  
HERO SECTION
RED SECTION