开发者问题收集

修复我的 querySelector,在 javaScript 中向其添加特定类

2022-02-06
811

我已经在我的网页中动态构建了导航栏,如下所示

NavBuilder = () => {
//to loop from section 1 to 4 and add sections to navigation 
for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `<a class="menu__link" href="#${Id}">${DataNav}</a>`;
    Menu.appendChild(liElem);
}
}
NavBuilder();

当我想要滚动页面时,我想将特定类“your-active-class”添加到我在 html 页面中创建的部分,同时将类“active”添加到 liElem,这样每当我在页面中滚动并停止在特定部分时,导航栏应该突出显示我在导航栏中停止的部分,并突出显示该部分本身。

我创建的用于添加类 active 的 javaScript 函数:

window.addEventListener('scroll', () => {
sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
        s.classList.add('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.add("active");

        // otherwise, remove the class
    } else {
        s.classList.remove('your-active-class');
        document.querySelector(`<a class="menu__link" href="#${sections[s].id}"></a>`).classList.remove("active");


    }
});

});

我仍然在行中捕获此错误“未捕获 TypeError:无法读取未定义的属性‘id’” document.querySelector( <a class="menu__link" href="#${sections[s].id}"></a> ).classList.add("active");

我犯了什么错误,导致我无法突出显示导航栏?

html 代码:

<!DOCTYPE>
<html lang="en">

<head>
</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">

<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>
    </main>
  <footer class="page__footer">
    <p>&copy Udacity</p>
  </footer>
  <script src="js/app.js"></script>
</body>

</html>

以及 active 类和 your-active-class

.active {
padding: 25px;
background-color: black;
color: white;

>

section.your-active-class {
background: rgb(0, 0, 0);
background: linear-gradient(0deg, rgba(211, 39, 39, 0.356) 0%, rgba(223, 10, 10, 0.548) 100%);

>

2个回答

querySelector 要求您向其传递一个有效的 CSS 选择器,但您没有这样做。您需要对其进行一些更改,然后根据 href 的值进行选择。

在 queryselector 中,您不能使用 <a> 语法。

document.querySelector(`a[href="#${sections[s].id}"]`)
Palladium02
2022-02-06

JS 中 foreach 循环 的基本语法为: forEach((element) => { /* ... */} )

其他语法:

// Arrow function
forEach((element) => { /* ... */ } )
forEach((element, index) => { /* ... */ } )
forEach((element, index, array) => { /* ... */ } )

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* ... */ })
forEach(function(element, index) { /* ... */ })
forEach(function(element, index, array){ /* ... */ })
forEach(function(element, index, array) { /* ... */ }, thisArg)

你代码中的变量 s 已经是元素 ,但不是索引(键)。直接使用 ${s.id> 即可。

此外,我们不以那种方式使用 querySelector() (通过输入其 HTML 来获取整个元素)。

您的代码可以替换为:

document.querySelector(`a[href="#${s.id}"]`)

有关 querySelector() 的更多信息,请访问 https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

P.S.另外,我真的很想知道你的页面中是否真的有一个名为 your-active-class 的类,因为它看起来像是你完全从网站上复制的 :P 如果没有,你可以简单地删除 s.classList.add('your-active-class');

NullVoid
2022-02-06