Vanilla JS change active state of links when scrolling refactoring

后端 未结 2 632
逝去的感伤
逝去的感伤 2020-12-17 06:22

I\'m trying to ditch jQuery from my upcoming projects. I found a way to create a sticky nav on scroll with pure Vanilla JS, and wanted the links on my navigation to change t

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 07:09

    You can get all sections and links using document.querySelectorAll(). On scroll iterate the list of section from last to first, until you find one that matches. Then remove the .active class from all links, and add it to the link at the active index.

    Note: You should use throttling to prevent the calling of changeLinkState multiple times in a second. Another option is to use the Intersection Observer API.

    const links = document.querySelectorAll('.links');
    const sections = document.querySelectorAll('section');
    
    function changeLinkState() {
      let index = sections.length;
    
      while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
      
      links.forEach((link) => link.classList.remove('active'));
      links[index].classList.add('active');
    }
    
    changeLinkState();
    window.addEventListener('scroll', changeLinkState);
    nav {
      position: fixed;
      top: 0;
      right: 0;
      width: 10em;
    }
    
    section {
      height: 100vh;
      margin: 1em 0;
      background: gold;
    }
    
    .active {
      background: silver;
    }
    
    
    
    Home
    About Us
    Services
    Clients
    Contact

提交回复
热议问题