简体   繁体   English

Javascript - 滚动到时如何使部分“活动”

[英]Javascript - How to make a section 'active' when scrolled to

I'm very new to JavaScript so apologies if I'm lacking clarity in any of my description.我对 JavaScript 很陌生,所以如果我的描述不够清晰,我深表歉意。

I've built a small website that has a java-script generated menu and I'm just wanting to add functionality to highlight a section (and make 'active') in the menu when scrolled to.我已经建立了一个具有 java 脚本生成菜单的小型网站,我只想添加功能以在滚动到菜单时突出显示菜单中的一个部分(并使“活动”)。 I've put together the following, which isn't throwing any errors in the console, so I'm unsure what I've missed:我将以下内容放在一起,不会在控制台中引发任何错误,所以我不确定我错过了什么:

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);
    }
  });
});

The 'your-active-class' class has some custom CSS setup so it will just change visibility in the menu. 'your-active-class' class 有一些自定义 CSS 设置,因此它只会改变菜单中的可见性。

Any help is really appreciated非常感谢任何帮助

This is how you would observe whether a DOM Element is within view, and apply/remove a classname to it.这就是您观察 DOM 元素是否在视图中,并对其应用/删除类名的方式。 If you look at your inspector, you'll see the 'active' class being added/removed when they enter and exit view.如果您查看检查器,您会看到“活动” class 在进入和退出视图时被添加/删除。

 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, 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,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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM