// Get the navbars
var navbararray = document.querySelectorAll(".sticky-navbar");
// rather than only operating on a single navbar, pass the whole array
window.onscroll = function () { myFunction(navbararray) };
// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction(navbararray) {
navbararray.forEach(navbar => {
//Get the inner container
var innercontainerarray = document.getElementsByClassName("future-page-wrapper");
var innercontainer = innercontainerarray[0];
// Get the offset position of the navbar
var sticky = navbar.offsetTop;
if (window.pageYOffset >= sticky + 250) {
navbar.classList.add("sticky");
innercontainer.classList.add("page-wrapper");
} else {
navbar.classList.remove("sticky");
innercontainer.classList.remove("page-wrapper");
}
});
}
1条答案
按热度按时间rryofs0p1#
看起来主要的问题是你显式地抓取了第一个导航栏并应用了粘性逻辑。相反,你需要迭代所有的导航栏并在循环中应用你的逻辑,如下所示:
getElementsByClassName
,而是使用了document.querySelectorAll('.sticky-navbar')
。这将为您提供一个包含上述类的所有对象的非活动数组(文档here)