如何解决Javascript - 如何在滚动到时使部分“活动”
我对 JavaScript 非常陌生,如果我的描述不够清晰,请见谅。
我已经建立了一个小型网站,它有一个由 java 脚本生成的菜单,我只是想添加功能以在滚动到菜单时突出显示一个部分(并使“活动”)。我整理了以下内容,它们不会在控制台中引发任何错误,所以我不确定我错过了什么:
const sectionHead = document.querySelectorAll('h2');
const sections = document.querySelectorAll('section');
const nav = document.querySelector('nav');
// build the nav
function navMenu(){
for(let section of sectionHead){
let listItem = document.createElement("li");
listItem.innerHTML = section.textContent;
nav.appendChild(listItem);
listItem.classList.add('menu__link');
listItem.addEventListener("click",()=>{
section.scrollIntoView({behavior: "smooth"});
});
};
}
navMenu();
const nav_items = document.querySelectorAll('.menu__link')
window.addEventListener("scroll",() => {
let current = "";
sections.forEach((section) => {
const sectionTop = section.offsetTop;
const sectionHeight = section.clientHeight;
if (pageYOffset >= sectionTop - sectionHeight / 3) {
current = section.getAttribute("id");
}
});
//set section as active
nav_items.forEach((li) => {
li.classList.remove("your-active-class");
section.classList.remove("your-active-class");
if (section.classList.contains(current)) {
section.classList.add("your-active-class");
//console.log (li.classList);
}
});
});
'your-active-class' 类有一些自定义 CSS 设置,因此它只会改变菜单中的可见性。
非常感谢任何帮助
解决方法
这是您观察 DOM 元素是否在视图中,并为其应用/删除类名的方式。如果您查看检查器,您会看到“活动”类在进入和退出视图时被添加/删除。
window.addEventListener("load",function() {
//Query objects on document load
const sections = document.querySelectorAll("section")
console.log(`We have ${sections.length} sections`)
// Create options for Observer:
const options = {
rootMargin: '100px 0px',threshold: [0.25,0.25,0]
}
// Create instance of IO:
let observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
entry.target.classList.add('active')
} else {
entry.target.classList.remove('active')
}
})
},options)
// Iterate over each queried el,and add observer:
sections.forEach(section => {
observer.observe(section)
})
})
section {
background-color: red;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 6rem auto;
transition: all 300ms ease-in-out;
}
.active {
background-color: rgba(0,255,0.3);
transition: all 300ms ease-in-out;
}
<section><div>This is the first section</div></section>
<section><div>This is the second</div></section>
<section><div>This is the third</div></section>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。