Javascript 导航栏不再滚动到页面的各个部分了?
我在导航栏上加了一个li,突然,每当我点击菜单项时,它就不再滚动了。我需要使用Javascript使导航栏滚动到我的分区 这是我用Javascript创建的导航栏Javascript 导航栏不再滚动到页面的各个部分了?,javascript,html,css,Javascript,Html,Css,我在导航栏上加了一个li,突然,每当我点击菜单项时,它就不再滚动了。我需要使用Javascript使导航栏滚动到我的分区 这是我用Javascript创建的导航栏 const navMenu = document.querySelectorAll("section"); const navList = document.getElementById("navbar__list"); const items = ["Section 1", "Section 2", "Section 3", "Se
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);
// 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");
}
});
以前,我只添加了a标记,并在addEventListener中以.menu项而不是.menu列表为目标,但一旦我将li标记添加到导航栏中,li的类就不起作用了。我不确定该编辑或更改什么这个系统的想法是,给菜单项一个id,然后使用id在这里滚动,而忘记给元素一个id。然后我把它放在你的点击事件中,使用这个id获取id并href到该部分
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");
console.log(event.target.id);
window.location.href="#section"+event.target.id
}
});
请创建一个JSFIDLE