gpt4 book ai didi

javascript - 创建粘性滚动导航栏时修复 "jump"

转载 作者:行者123 更新时间:2023-11-28 02:20:35 29 4
gpt4 key购买 nike

粘性导航栏“跳跃”

我最近制作了一个导航栏,它在滚动时粘在屏幕顶部(进入网页时它从中间开始)。我是在 Mac 上做的,一切正常。但是,当在我的 Windows 桌面上进入网页时,整个导航栏要么跳动,跳过一些内容,要么出现故障,使我无法进一步向下滚动。

1) 是 macOS/windows 或 safari/chrome 之间的区别导致了这种情况发生吗?

2) 我该如何解决?

// When the user scrolls the page, execute myFunction 
window.onscroll = function() {stickyNavbar()};
// Get the header
var header = document.getElementById("navbar");
// Get the offset position of the navbar
var sticky = header.offsetTop;
// Add the sticky class to the header when you reach its scroll position.
// Remove "sticky" when you leave the scroll position
function stickyNavbar() {
if (window.pageYOffset > sticky ) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
.navbar{
display: grid;
grid-template-columns: repeat(3, auto);
background-image: url(resources/navbar.png);
width: 100%;
background-size: contain;
}

.sticky{
position: fixed;
top: 0;
width: 100%;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
}

section {
height: 1000px;
border: 1px solid red;
}
  
<body>
<img class="header-image" src="resources/header.PNG" alt="">
<nav class="navbar" id="navbar">
<div><a href="pages/gallery.html">Galleri</a></div>
<div class="active"><a href="index.html"><img class="boat-logo" src="resources/logo.png" alt=""></a></div>
<div><a href="pages/timeline.html">Historikk</a></div>
</nav>

<section class="content"></section>
</body>

最佳答案

一直使用position: sticky,那么就不需要监听滚动事件或计算尺寸和偏移,让浏览器为你做。

.navbar{
display: grid;
grid-template-columns: repeat(3, auto);
background-image: url(resources/navbar.png);
width: 100%;
background-size: contain;
}

.sticky{
position: sticky;
top: 0;
width: 100%;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
}

section {
height: 1000px;
border: 1px solid red;
}
  
<body>
<img class="header-image" src="resources/header.PNG" alt="">
<nav class="navbar sticky" id="navbar">
<div><a href="pages/gallery.html">Galleri</a></div>
<div class="active"><a href="index.html"><img class="boat-logo" src="resources/logo.png" alt=""></a></div>
<div><a href="pages/timeline.html">Historikk</a></div>
</nav>

<section class="content"></section>
</body>

关于javascript - 创建粘性滚动导航栏时修复 "jump",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910573/

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