1 回答

TA貢獻1807條經驗 獲得超9個贊
系統的想法是給菜單項一個 id 并使用 id 在這里滾動你忘了給 element 提供 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
}
});
- 1 回答
- 0 關注
- 156 瀏覽
添加回答
舉報