我最近制作了一个导航栏,该导航栏在滚动时停留在屏幕顶部(在进入网页时从中间开始)。我在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>
答案 0 :(得分:0)
如果将位置更改为粘性,是否也会遇到相同的问题?
sticky{
position: sticky;
top: 0;
width: 100%;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
}
window.onscroll = function() {stickyNavbar()};
// Get the header
var header = document.getElementById("navbar");
// Get the offset position of the navbar
var sticky = window.scrollY + header.getBoundingClientRect().top;
// 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");
}
}
您还可以使用一个防反跳功能,以便在计算之前先保留一下。同样对性能也很重要:
答案 1 :(得分:0)
始终使用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>