javascript - 如何使用 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。
解决方案
首先,您可以使用以下代码代替重复,它执行相同的任务
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
推荐阅读
- javascript - 获取客户端javascript代码中可用的node.js服务器端对象
- r - 使用特定列的值从其他行中减去,但列索引在 R 中的文件之间移动
- spring - 使用反应式 DB 客户端扩展 Spring WebFlux 应用程序时出现问题:Maven 依赖项冲突?
- git - 如何 grep Git 提交消息或关键字的差异并输出更改(聚合)的文件名?
- javascript - CakePHP scriptBlock 没有在 HTML 页面中添加任何 JavaScript
- node.js - 为什么我不能直接使用 req.body 作为参数?
- javascript - React Native,为什么 react-native run-android 不起作用?
- hadoop - 使用 cygwin 在窗口 10 上配置 Hive:路径错误
- python - 在 pylint 和 mypy 中处理 Python 类重新定义警告
- javascript - 在部署在不同域上的两个仅客户端 JS 应用程序之间共享本地 blob 数据