gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:23:44 24 4
gpt4 key购买 nike

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

Fiddle

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

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

最佳答案

编辑

我添加了 slideDown 功能,如评论中所问...
而且看起来很棒!

关于这个添加有两点要说:

  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()<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>

此代码段在整页模式下效果更佳
(否则高度太小会闪烁)

关于javascript - 到达英雄部分底部时,将静态导航栏更改为固定在滚动条上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43302338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com