简体   繁体   English

每当我滚动浏览该部分时,突出显示我的导航栏菜单项? 仅使用 Javascript

[英]Highlight my navbar menu items whenever I scroll through that section? Only using Javascript

I currently have my nav menu items highlighted whenever I click them, but I want the entire section in the HTML to have a highlighted background, so when the user is scrolling through the website, it will automatically highlight the nav menu item according to the whichever section they are scrolling through我目前每次单击时都会突出显示导航菜单项,但我希望 HTML 中的整个部分具有突出显示的背景,因此当用户滚动浏览网站时,它将自动突出显示导航菜单项他们正在滚动浏览的部分

Here is an example on codepen that I'm trying to achieve with my code https://codepen.io/joxmar/pen/NqqMEg这是我试图用我的代码https://codepen.io/joxmar/pen/NqqMEg实现的 codepen 示例

Here is my current landing page in Jsfiddle https://jsfiddle.net/hzg02k3n/这是我当前在 Jsfiddle https://jsfiddle.net/hzg02k3n/中的登录页面

As you can see from my jsfiddle, the links get highlights when I click, but I need it to become active whenever I scroll over the section.正如您从我的 jsfiddle 中看到的那样,当我单击链接时,链接会突出显示,但每当我滚动该部分时,我需要它变为活动状态。

Below my current HTML code在我当前的 HTML 代码下方

<header class="page__header">
      <nav class="navbar__menu">
        <!-- Navigation starts as empty UL that will be populated with JS -->
        <ul id="navbar__list"></ul>
      </nav>
    </header>
    <main>
      <header class="main__hero">
        <h1>Landing Page</h1>
      </header>
<section id="section1" data-nav="Section 1" class="active">
        <div class="landing__container">
          <h2>Section 1</h2>
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
            fermentum metus faucibus lectus pharetra dapibus. Suspendisse
            potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget
            lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed
            convallis sollicit
          </p>

          <p>
            Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar
            gravida, ipsum l
          </p>
        </div>
      </section>
      <section id="section2" data-nav="Section 2">
        <div class="landing__container">
          <h2>Section 2</h2>
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
            fermentum metus faucibus lectus pharetra dapibus. Suspendisse
            potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget
            lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed
            convallis s
          </p>

          <p>
            Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar
            gravida, ipsum l
          </p>
        </div>
      </section>

I have up to 4 sections, but this just shows the first two.我最多有 4 个部分,但这仅显示前两个部分。

Here is my Javascript that I used to create the navbar这是我用来创建导航栏的 Javascript

const navMenu = document.querySelectorAll("section");
const navList = document.getElementById("navbar__list");
const items = ["Section 1", "Section 2", "Section 3", "Section 4"];

//Build the nav
items.forEach((item, i) => {
  const el = document.createElement("a");
  el.innerText = item;
  el.classList.add("menu-items");
  el.setAttribute("id", `menu-${i + 1}`);
  el.href = `#section${i + 1}`;
  navList.appendChild(el);

  const li = document.createElement("li");
  li.classList.add("menu-list");
  li.appendChild(el);
  li.setAttribute("id", `${i + 1}`);
  // Append the list item to the list
  navList.appendChild(li);
});

//Make Nav Active when Clicked and scrolls down to section
document.addEventListener("click", function (event) {
  let active = document.querySelector(".menu-list.active");
  if (active) active.classList.remove("active");
  if (event.target.classList.contains("menu-list")) {
    event.target.classList.add("active");
    window.location.href = "#section" + event.target.id;
  }
});

Just utilize the mouseover and mouseout events!只需利用mouseovermouseout事件!

Here is a small example & here is a JS Fiddle as well :这是一个小例子&这里也是一个 JS Fiddle

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <style>
      body {
        font-family : "Arial", sans-serif;
      }

      #navbar__list {
        height           : 40px;
        background-color : #55443D;
        display          : block;
        align-content    : center;
        align-items      : center;
        position         : fixed;
        top              : 0;
        left             : 0;
        width            : 100vw;
        z-index          : 1;
        margin           : 0 auto;

      }

      #navbar__list ul {
        padding    : 0;
        list-style : none;
        position   : relative;
        display    : table;
        margin     : 0 auto;
      }

      #navbar__list li {
        display : table-cell;
      }

      #navbar__list li a {
        padding         : 10px 20px;
        display         : block;
        color           : white;
        text-decoration : none;
        transition      : all 0.3s ease-in-out;
      }

      #navbar__list li a:hover {
        color : #dc5c26;
      }

      #navbar__list li a .active {
        color         : #F38A8A;
        border-bottom : 3px solid #F38A8A;
      }

      .active {
        color         : #F38A8A;
        border-bottom : 3px solid #F38A8A;
      }

      .sec {
        height  : 50vh;
        display : block;
      }

      .sec h2 {
        position : relative;
        top      : 50%;
        left     : 50%;
      }

      #section1 {
        background-color : green;
      }

      #section2 {
        background-color : yellow;
      }

      #section3 {
        background-color : blue;
      }

      #section4 {
        background-color : grey;
      }
    </style>
  </head>
  <body>
    <ul id="navbar__list"></ul>

    <section class="container">
      <div id="section1" class="sec">
        <h2>Section 1</h2>
      </div>
      <div id="section2" class="sec">
        <h2>Section 2</h2>
      </div>
      <div id="section3" class="sec">
        <h2>Section 3</h2>
      </div>
      <div id="section4" class="sec">
        <h2>Section 4</h2>
      </div>
    </section>
  </body>
  <script>
    const navMenu = document.querySelectorAll( "section" );
    const navList = document.getElementById( "navbar__list" );
    const items = [ "Section 1", "Section 2", "Section 3", "Section 4" ];
    let lastId;
    let last_known_scroll_position = 0;
    let ticking = false;

    //Build the nav
    items.forEach( ( item, i ) => {
      const li = document.createElement( "li" );
      const el = document.createElement( "a" );
      el.innerText = item;
      el.classList.add( "menu-items" );
      el.setAttribute( "id", `menu-${i + 1}` );
      el.href = `#section${i + 1}`;

      el.addEventListener( "click", function ( e ) {
        const href = e.target.getAttribute( "href" ),
          offsetTop = href === "#" ? 0 : e.target.offsetTop - topMenuHeight + 1;
        const scrollOptions = { scrollIntoView: true, behavior: "smooth" };
        e.target.scrollIntoView( scrollOptions );
        e.preventDefault();
      } );

      navList.appendChild( li );
      li.appendChild( el );
    } );

    const topMenu = document.getElementById( "navbar__list" );
    const topMenuHeight = topMenu.offsetHeight + 1;
    const menuItems = document.querySelectorAll( ".menu-items" );
    const scrollItems = document.querySelectorAll( ".sec" );

    //Make Nav Active when Clicked and scrolls down to section
    document.addEventListener( "click", function ( event ) {
      let active = document.querySelector( ".active" );
      if ( active ) {
        active.classList.remove( "active" );
      }
      if ( event.target.classList.contains( "menu-items" ) ) {
        event.target.classList.add( "active" );
      }
    } );

    // Bind to scroll
    window.addEventListener( "scroll", function () {
      // Get container scroll position
      const container = document.querySelector( ".container" );
      let fromTop = window.pageYOffset + topMenuHeight + 40;

      // Get id of current scroll item
      let cur = [];

      [ ...scrollItems ].map( function ( item ) {
        if ( item.offsetTop < fromTop ) {
          cur.push( item );
        }
      } );

      // Get the id of the current element
      cur = cur[ cur.length - 1 ];
      let id = cur ? cur.id : "";

      if ( lastId !== id ) {
        lastId = id;

        menuItems.forEach( function ( elem, index ) {
          elem.classList.remove( "active" );
          const filteredItems = [ ...menuItems ].filter( elem => elem.getAttribute( "href" ) === `#${id}` );
          filteredItems[ 0 ].classList.add( "active" );
        } );
      }
    } );
  </script>
</html>

Edit: This is the working fiddle using your code编辑:这是使用您的代码的工作小提琴

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

相关问题 当我滚动到每个有缺陷的部分时,菜单项变得突出 - menu items getting highlight as I scroll to each section with deficiency 我想使用 Javascript 在引导导航栏中突出显示当前部分和当前页面 - I want to Highlight the current section and current page in the bootstrap navbar using Javascript 在React中滚动时,如何使导航栏突出显示? - How do I make my navbar highlight as I scroll in React? 使用JS突出显示菜单项 - Using JS to highlight menu items 仅使用JavaScript在导航栏外部单击后关闭下拉菜单吗? - Close dropdown menu after click outside of navbar using only JavaScript? 导航栏没有隐藏在使用 javascript 的滚动上 - Navbar is not hiding on scroll using javascript 使用 Javascript 在导航栏中突出显示当前页面 - Using Javascript to highlight current page in navbar 如何使用 javascript 创建导航菜单 li? 以及如何在单击菜单选项后平滑滚动到部分? - How to create a Nav menu li using javascript? And how to scroll smoothly to section after clicking the menu option? 如何在 React 或 JavaScript 中隐藏导航栏或任何其他关于向下滚动的部分? - How To Hide Navbar or any others section on Scroll Down in React or JavaScript? 使用JavaScript滚动浏览ASP.NET MVC中的项目列表 - Using JavaScript to scroll through a list of items in ASP.NET MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM