当一个是锚链接描述列表,另一个是 ID 列表时,如何比较两个 nodeList

how do you compare two nodeList when one is a list of anchor link descriptions and the other is a list of ids

提问人:justin white 提问时间:11/10/2023 最后编辑:justin white 更新时间:11/10/2023 访问量:24

问:

我的问题是,当用户滚动到与该链接对应的部分时,尝试让导航栏链接突出显示。我能够在单击时突出显示链接,但在滚动页面时无法突出显示。我使用 app.js 文件中第 58 行的事件侦听器来比较链接和部分 ID,然后尝试将链接类更改为活动。从那里,在CSS文件中,我控制活动类并突出显示链接。我的问题是我的 EventListener 函数不起作用,或者它可能是导致问题以外的其他原因。

let navbar = document.getElementById("navbar__list");

/**
 * End Global Variables
 * Start Helper Functions
 *
 */

/**
 * End Helper Functions
 * Begin Main Functions
 */

// build the nav

let first = document.createElement("li");
first.innerHTML = '<a href="#">section1</a>';
navbar.appendChild(first);

let second = document.createElement("li");
second.innerHTML = '<a href="#">section2</a>';
navbar.appendChild(second);

let third = document.createElement("li");
third.innerHTML = '<a href="#">section3</a>';
navbar.appendChild(third);

let fourth = document.createElement("li");
fourth.innerHTML = '<a href="#">section4</a>';
navbar.appendChild(fourth);

// Add class 'active' to section when near top of viewport
/*function updateActiveSection() {*/
window.addEventListener("scroll", function (href) {
  // Get all sections that have an ID defined.
  const sections = document.querySelectorAll("section");
  const navlight = document.querySelectorAll("a");
  for (let i = 0; i < sections.length; i++) {
    if (sections[i].id === navlight[i].hash.split()[1]) {
      navlight[i].classList.add("active");
    } else {
      navlight[i].classList.remove("active");
    }
    for (const section of sections) {
      const rect = section.getBoundingClientRect();
      if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
        // The section is in the viewport, so add the "active" class.
        section.classList.add("active");
      } else {
        // The section is not in the viewport, so remove the "active" class.
        section.classList.remove("active");
      }
    }
  }
});

// Add an event listener for the scroll event.
window.addEventListener("scroll", window);

// Scroll to anchor ID using scrollTO event
function scrollIntoView(id) {
  var element = document.getElementById(id);
  if (element) {
    element.scrollIntoView({
      behavior: "smooth",
    });
  }
}
/*

* End Main Functions
 * Begin Events
 *
 */

// Build menu

// Scroll to section on link click
first.addEventListener("click", function (event) {
  event.preventDefault();
  scrollIntoView("section1");
  /*if (event) {
    first.classList.add("active"); //set active to link
  }*/
});
first.addEventListener("mouseout", function (event) {
  first.classList.remove("active"); // remove active from link when out of container
});

second.addEventListener("click", function (event) {
  event.preventDefault();
  scrollIntoView("section2");
  if (event) {
    second.classList.add("active"); //set active to link
  }
});
second.addEventListener("mouseout", function (event) {
  second.classList.remove("active"); // remove active from link when out of container
});

third.addEventListener("click", function (event) {
  event.preventDefault();
  scrollIntoView("section3");
  if (event) {
    third.classList.add("active"); //set active to link
  }
});
third.addEventListener("mouseout", function (event) {
  third.classList.remove("active"); // remove active from link when out of container
});

fourth.addEventListener("click", function (event) {
  event.preventDefault();
  scrollIntoView("section4");
  if (event) {
    fourth.classList.add("active"); //set active to link
  }
});
fourth.addEventListener("mouseout", function (event) {
  fourth.classList.remove("active"); // remove active from link when out of container
});
body {
    background: rgb(136,203,171);
    background: linear-gradient(0deg, rgba(136,203,171,1) 0%, rgba(0,13,60,1) 100%);
    margin: 0;
    font-family: 'Merriweather', serif;
    color: #fff;
}


/* Typeography General*/
h1 {
    font-family: 'Fira Sans', sans-serif;
    font-size: 3em;
    margin: 2em 1rem;
}

@media only screen and (min-width: 35em){
    h1 {
        font-size: 7em;
        margin: 2em 4rem 1em;
    }
}

h2 {
    border-bottom: 1px solid #cc1;
    font-family: 'Oxygen', Sans-Serif;
    font-size: 3em;
    color: #fff;
}

p {
    line-height: 1.6em;
    color: #eee;
}

/* ---- Layout Rules ---- */
main {
    margin: 10vh 1em 10vh;
}

.main-hero {
    min-height: 40vh;
    padding-top: 3em;
}

section {
    position: relative;
    min-height: 80vh;
}


/* ---- Module Rules ---- */

/* Navigation Styles*/
.navbar__menu ul {
    padding-left: 0;
    margin: 0;
    text-align: right;
}

.navbar__menu li {
    display: inline-block;
    padding: 2em;
    font-family: 'Fira Sans', sans-serif;
   
}
a:hover{
    color:rgb(78, 161, 234);
    background-color: transparent;
    
}

.navbar__menu .menu__link {
    display: block;
    padding: 4em;
    font-weight: bold;
    text-decoration: none;
    color: #000;
}

.navbar__menu .menu__link:hover {
    background: #333;
    color: #fff;
    transition: ease 0.3s all;
}
li.active {
    border: solid 3px rgb(78, 161, 234);
    background-color:rgb(205, 237, 73);
}

/* Header Styles */
.page__header {
    background: #10234a;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 5;
}

/* Footer Styles */
.page__footer {
    background: #000;
    padding: 3em;
    color: #fff;
}

.page__footer p{
    color: #fff;
}


/* ---- Theme Rules ---- */
/* Landing Container Styles */
.landing__container {
    padding: 1em;
    text-align: left;
}

@media only screen and (min-width: 35em){
    .landing__container {
        max-width: 50em;
        padding: 4em;
    }
}

section:nth-of-type(even) .landing__container {
    margin-right: 0;
    margin-left: auto;
    text-align: right; 
}

/* Background Circles */
/* Note that background circles are created with psuedo elements before and after */
/* Circles appear to be random do to use of :nth-of-type psuedo class */
section:nth-of-type(odd) .landing__container::before {
    content: '';
    background: rgba(255, 255, 255, 0.187);
    position: absolute;
    z-index: -5;
    width: 20vh;
    height: 20vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}

section:nth-of-type(even) .landing__container::before {
    content: '';
    background: rgb(255,255,255);
    background: linear-gradient(0deg, rgba(255,255,255,.1) 0%, rgba(255,255,255,.2) 100%);
    position: absolute;
    top: 3em;
    right: 3em;
    z-index: -5;
    width: 10vh;
    height: 10vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}

section:nth-of-type(3n) .landing__container::after {
    content: '';
    background: rgb(255,255,255);
    background: linear-gradient(0deg, rgba(255,255,255,.1) 0%, rgba(255,255,255,.2) 100%);
    position: absolute;
    right: 0;
    bottom: 0;
    z-index: -5;
    width: 10vh;
    height: 10vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}

section:nth-of-type(3n + 1) .landing__container::after {
    content: '';
    background: rgb(255,255,255);
    background: linear-gradient(0deg, rgba(255,255,255,.1) 0%, rgba(255,255,255,.2) 100%);
    position: absolute;
    right: 20vw;
    bottom: -5em;
    z-index: -5;
    width: 15vh;
    height: 15vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}


/* ---- Theme State Rules ---- */
/* Section Active Styles */
/* Note: your-active-class class is applied through javascript. You should update the class here and in the index.html to what you set in your javascript file.  */
section.active {
    background: rgb(205, 237, 73);
    background: linear-gradient(0deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 100%);
}

section.active.landing__container::before {
    opacity: 1;
    animation: rotate 4s linear 0s infinite forwards;
}

section.active .landing__container::after {
    background: rgb(205, 237, 73);
    opacity: 1;
    animation: rotate 5s linear 0s infinite forwards reverse;
}

/* Section Active Styles Keyframe Animations */
@keyframes rotate {
    from {
        transform: rotate(0deg)
                   translate(-1em)
                   rotate(0deg);
    }
    to {
        transform: rotate(360deg)
                   translate(-1em) 
                   rotate(-360deg);
    }
}
<!DOCTYPE >
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Manipulating the DOM</title>
    <!-- Load Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap"
      rel="stylesheet"
    />
    <!-- Load Styles -->
    <link href="css/styles.css" rel="stylesheet" />
  </head>
  <body>
    <!-- HTML Follows BEM naming conventions 
  IDs are only used for sections to connect menu achors to sections -->
    <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>
      <!-- Each Section has an ID (used for the anchor) and 
    a data attribute that will populate the li node.
    Adding more sections will automatically populate nav.
    The first section is set to active class by default -->
      <section id="section1" data-nav="Section 1">
        <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 sollicitudin mauris ac tincidunt. Donec bibendum, nulla
            eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam
            nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis
            lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a
            tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus
            vitae elit. Integer nec libero venenatis libero ultricies molestie
            semper in tellus. Sed congue et odio sed euismod.
          </p>

          <p>
            Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar
            gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam.
            Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum
            consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget
            elementum tortor mollis non.
          </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 sollicitudin mauris ac tincidunt. Donec bibendum, nulla
            eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam
            nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis
            lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a
            tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus
            vitae elit. Integer nec libero venenatis libero ultricies molestie
            semper in tellus. Sed congue et odio sed euismod.
          </p>

          <p>
            Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar
            gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam.
            Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum
            consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget
            elementum tortor mollis non.
          </p>
        </div>
      </section>
      <section id="section3" data-nav="Section 3">
        <div class="landing__container">
          <h2>Section 3</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 sollicitudin mauris ac tincidunt. Donec bibendum, nulla
            eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam
            nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis
            lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a
            tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus
            vitae elit. Integer nec libero venenatis libero ultricies molestie
            semper in tellus. Sed congue et odio sed euismod.
          </p>

          <p>
            Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar
            gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam.
            Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum
            consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget
            elementum tortor mollis non.
          </p>
        </div>
      </section>
      <section id="section4" data-nav="Section 4">
        <div class="landing__container">
          <h2>Section 4</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 sollicitudin mauris ac tincidunt. Donec bibendum, nulla
            eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam
            nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis
            lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a
            tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus
            vitae elit. Integer nec libero venenatis libero ultricies molestie
            semper in tellus. Sed congue et odio sed euismod.
          </p>

          <p>
            Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar
            gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam.
            Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum
            consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget
            elementum tortor mollis non.
          </p>
        </div>
      </section>
    </main>
    <footer class="page__footer">
      <p>&copy Udacity</p>
    </footer>

    <script src="./js/app.js"></script>
  </body>
</html>

JavaScript 迭代 比较

评论

0赞 Barmar 11/10/2023
欢迎来到 Stack Overflow!请发布一个最小的可重现示例。您可以使用堆栈代码段使其可执行。从你的描述中不清楚你要做什么,以及你的代码有什么问题。
0赞 Barmar 11/10/2023
ID 列表如何成为 NodeList?它似乎是一个字符串数组。
0赞 justin white 11/10/2023
我是这个消息来源的新手,说这是一个节点列表,但它可以迭代,但我正在努力获得结果,我寻求任何帮助,非常感谢谢谢巴马尔
0赞 Barmar 11/10/2023
为什么在嵌套在第一个部分的部分上有第二个循环?它在任何地方都用不上。要么它应该在循环之外,要么你应该只做其他事情而不是循环。isections[i]
0赞 justin white 11/10/2023
我已经按照您的要求输入了一个堆栈片段,并试图在我的问题中更具描述性。

答: 暂无答案