3 回答

TA贡献1830条经验 获得超9个赞
要forEach
在 HTML 集合上使用,您必须将其展开到一个数组中:
let allLists = [...document.querySelectorAll("li")];

TA贡献1796条经验 获得超10个赞
问题出在这一行:
allSections[index].scrollIntoView({ behavior: "smooth" });
由于您正在使用 allLists(LI) 索引来访问 allSections(section),因此您希望具有相同数量的部分和 li。
我建议向ignore以下LI元素添加一个类:
<li class="ignore" id="new-section">NEW SECTION</li>
<li class="ignore" id="back">BACK TO TOP</li>
只要您拥有与 LI 元素相同数量的 SECTION 元素(不包括 2 个被忽略的元素),那么您就不会收到错误。
更新:我已经更正了以下行(之前有一个#)。确保两个allLists作业都已更新:
allLists = document.querySelectorAll("li:not(.ignore)");
注意:由于allLists循环现在处于scroll事件中,因此在用户滚动之前它不会被初始化。
var newSectionBtn = document.getElementById("newSectionBtn");
let allSections = document.querySelectorAll("section");
let allLists = document.querySelectorAll("li:not(.ignore)");
let n = 4;
// This function runs wherever the user press add new section button.
function duplicate(num) {
const newSection = document.createElement("section");
const newDiv = document.createElement("div");
const heading = document.createElement("h2");
const p1 = document.createElement("p");
const p2 = document.createElement("p");
newSection.appendChild(newDiv);
newDiv.appendChild(heading);
newDiv.appendChild(p1);
newDiv.appendChild(p2);
newSection.setAttribute("id", "section" + num);
newSection.setAttribute("data-nav", "Section" + " " + num);
newDiv.setAttribute("class", "landing__container");
heading.textContent = "Section" + " " + num;
p1.textContent =
"New text";
p2.textContent =
"New text";
return newSection;
}
// Append the above function to the body.
newSectionBtn.addEventListener("click", () => {
newSectionBtn.insertAdjacentHTML("beforebegin", "<li> Section" + " " + n + "</li>");
main.appendChild(duplicate(n));
main.lastElementChild.scrollIntoView({ behavior: "smooth" });
n++;
});
window.addEventListener("scroll", () => {
allLists.forEach((list, index) => {
list.addEventListener("click", () => {
allSections[index].scrollIntoView({ behavior: "smooth" });
allSections = document.querySelectorAll("section");
allLists = document.querySelectorAll("li:not(.ignore)");
});
});
});
<button id="newSectionBtn">Hello</button>
<main id="main">
<header class="main__hero">
<nav>
<ul class="flex-container">
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
<li class="ignore" id="new-section">NEW SECTION</li>
<li class="ignore" id="back">BACK TO TOP</li>
</ul>
</nav>
<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>
</main>
添加回答
举报