首页 > 解决方案 > 如何使用 javascript 创建导航菜单 li?以及如何在单击菜单选项后平滑滚动到部分?

问题描述

我正在尝试仅使用 Javascript 创建具有 4 个选项的导航菜单。我正在尝试将其插入 ID 为“navbar__list”的“ul”中,并且我想通过 JS 创建带有类和 ID 的 li。这是我到目前为止所做的,但我知道我的代码似乎重复,我不知道如何使它更简洁。

const navMenu = document.querySelectorAll("section");
const navList = document.getElementById("navbar__list");

//Attempt to build the Nav Menu
const navItem1 = document.createElement("a");
navItem1.classList.add("menu-items");
navItem1.setAttribute("id", "menu-1");
navItem1.innerText = "Section 1";
navItem1.href = "#section1";
navList.appendChild(navItem1);

const navItem2 = document.createElement("a");
navItem2.classList.add("menu-items");
navItem2.setAttribute("id", "menu-2");
navItem2.innerText = "Section 2";
navItem2.href = "#section2";
navList.appendChild(navItem2);

const navItem3 = document.createElement("a");
navItem3.classList.add("menu-items");
navItem3.setAttribute("id", "menu-3");
navItem3.innerText = "Section 3";
navItem3.href = "#section3";
navList.appendChild(navItem3);

const navItem4 = document.createElement("a");
navItem4.classList.add("menu-items");
navItem4.setAttribute("id", "menu-4");
navItem4.innerText = "Section 4";
navItem4.href = "#section4";
navList.appendChild(navItem4);

我还想创建一个滚动效果,所以每当我点击菜单选项时,它都会平滑地滚动到我的 HTML 中的部分。每个部分都是标签 Section1 - Section4。

标签: javascripthtmlcss

解决方案


首先,您可以使用以下代码代替重复,它执行相同的任务

const navList = document.getElementById("navbar__list");

for(let i=1; i<5; i++){
    const navItem = document.createElement("a");
    navItem.classList.add("menu-items");
    navItem.setAttribute("id", `menu-${i}`);
    navItem.innerText = `Section ${i}`;
    navItem.href = `#menu-${i}`;
    navList.appendChild(navItem);
}

我相信这将解决第一个问题。

其次,为了平滑滚动。在你的 CSS 屁股里

html,body{
   scroll-behavior: smooth;
}

有关平滑滚动的更多信息,请查看此https://www.w3schools.com/howto/howto_css_smooth_scroll.asp


推荐阅读