gpt4 book ai didi

javascript - 到达特定部分的底部时如何将静态位置更改为固定位置

转载 作者:太空宇宙 更新时间:2023-11-04 09:03:39 26 4
gpt4 key购买 nike

我刚开始学习 jQuery 和 JS,但我现在在制作一些基本的东西时遇到困难。

我想让静态导航栏在窗口到达 .hero-fullscreen 部分的末尾时固定,否则返回静态。

$(window).on("scroll", function() {

var navbar = $(".navbar");
if (navbar.offset().top > 150) {
navbar.addClass(".navbar-fixed");
} else {
navbar.removeClass(".navbar-fixed");
}

});
.navbar {
display: block;
height: 50px;
width: 100%;
background-color: #000;
}

.navbar-static {
position: static;
}

.navbar-fixed {
position: fixed;
}

.hero-fullscreen {
height: 100vh;
width: 100%;
background-color: red;
}

.random-section {
height: 100vh;
width: 100%;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-static"></nav>
<section class="hero-fullscreen bg-image"></section>
<section class="random-section"></section>

现在,我的问题是,不是 .top > 150,而是应该放什么,以便 navbar 在到达 的底部时固定。 hero-fullscreen(红色部分)?

谢谢!

最佳答案

基本上你需要做两件事:

  1. 找出视口(viewport)的高度
  2. 始终跟踪滚动条是

像这样

    window.addEventListener('load', getWindowHeight);
window.addEventListener('resize', getWindowHeight);

var endPos;

function getWindowHeight(){
var hei = window.innerHeight;
endPos = hei + 50;
}

document.addEventListener('scroll', trackScroll);

var navBar = document.getElementById('navbar');

function trackScroll() {
var scrollPos = document.body.scrollTop();
if (scrollPos > endPos) {
navBar.style.position = 'fixed';
} else {
navBar.style.position = 'static';
}
}

但是,我这样做是为了让您必须为导航元素提供 navbarid,而不是 class .

  1. getWindowHeight 满足第一个要求。
  2. trackScroll 满足第二个要求并进行必要的更改。

关于javascript - 到达特定部分的底部时如何将静态位置更改为固定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42602129/

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