问题是当我单击导航栏中的链接时,它不会转到其部分



我正在尝试制作一个动态导航栏,当我点击链接时,它会转到它的特定部分,我使用了以下代码:

//scroll to section when click on nav links
li_links.addEventListener('click', e => {
e.preventDefault();
section.scrollIntoView()
});

为什么当我点击链接时,它会转到页面的末尾,而不是指定的部分?

这是代码:

const Ul = document.querySelector('ul');
const sections = document.querySelectorAll('section');
for(section of sections) {
//create li:
const li_items = document.createElement("li");

//create new anchor elements:
const li_links = document.createElement("a");

//give anchor elements a hyperlinks:
const IdAttribute = section.getAttribute('id');
li_links.setAttribute('href', IdAttribute);
//get the names of the sections:
const navData = section.getAttribute("data-nav");
const text = document.createTextNode(navData);

//give the navbar style :
li_links.classList.add("menu__link");
Ul.appendChild(li_items);
li_items.appendChild(li_links);
li_links.appendChild(text);
//scroll to section when click on nav links
li_links.addEventListener('click', e => {
e.preventDefault();
section.scrollIntoView()
});
}
//end of the navbar.

HTML代码:

<header id="hdr" 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="your-active-class">
<div class="landing__container">
<h2>Section 1</h2>
<p></p>
<p></p>
</div>
</section>
<section id="section2" data-nav="Section 2">
<div class="landing__container">
<h2>Section 2</h2>
<p></p>
<p></p>
</div>
</section>
<section id="section3" data-nav="Section 3">
<div class="landing__container">
<h2>Section 3</h2>
<p></p>
<p></p>
</div>
</section>
<section id="section4" data-nav="Section 4">
<div class="landing__container">
<h2>Section 4</h2>
<p></p>
<p></p>
</div>
</section>

代码笔上的代码:CodePen

使用constlet声明块范围的变量

for(const section of sections) {

否则,section在函数范围内,并为循环的每次迭代重新分配。因此,当事件发生时,它们将指向section的最后一个值。

读取https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#description

最新更新