javascript - 使用 JavaScript 滚动功能导航到适当的部分

标签 javascript scrollto

我的目标是使用 JavaScript 完成一个动态单一登陆页面。 HTML 和 CSS 文件已经提供,我设法通过操作 DOM 构建了一个无序列表。

让我陷入困境的是:当单击导航菜单中的某个项目时,链接应该滚动到适当的部分。 我无法让它工作:/

下面是到目前为止的 JS 代码。

/* Declare variables for the fictive document and menu list to retrieve and store variables as unordered list */
const container = document.createDocumentFragment();
const menuList = document.getElementsByTagName('section');

/* Function to create the navigation menu as a clickable link */
function navigationLink(id, name) {
    const navLink = `<a class = "menu__link" data-id=${id}">${name}</a>`;
    return navLink;
}

/* Function for the navigation list, built as an unordered list */
function createNavigation() {
    for (let i = 0; i < menuList.length; i++) {
        const newMenuListItem = document.createElement('li');
        const menuListName = menuList[i].getAttribute('data-nav')
        const menuListID = menuList[i].getAttribute('id')
        newMenuListItem.innerHTML = navigationLink(menuListID, menuListName)
        container.appendChild(newMenuListItem);
    }
    /* Retrieve the id from the ul section to be added to the document fragment: container */
    const navBarMenu = document.getElementById('navbar__list')
    navBarMenu.appendChild(container);
}

// Add class 'active' to section when near the top of viewport
function setActiveClass() {
    for (let i = 0; i < menuList.length; i++) {
        if (isInViewport(menuList[i])) {
            menuList[i].classList.add("your-active-class");
        } else {
            menuList[i].classList.remove("your-active-class");
        }
    }
}

为了解决这个问题,我研究了另一段无法正常运行的代码。

function scrollToElement(event) {
    if (event.target.nodeName === 'A') {
        const menuListID = event.target.getAttribute('data-id');
        const menu = document.getElementById(menuListID);
        menu.scrollIntoView({ behavior: "smooth" });
    }
}
document.addEventListener('scroll', function () {
    setActiveClass();
});

const navBarMenu = document.getElementById('navbar__list')
navBarMenu.addEventListener('click', function (event) {
    scrollToElement(event)
})

最佳答案

您可以使用 anchor 来执行此操作。这将使您的生活比尝试在 js 中执行此操作更轻松。

要使用它,您只需设置 id到一个节点。喜欢<div id="myFirstId"></div>然后,设置href您的链接到 #myFirstId .

如果您希望滚动不是即时的,您可以添加 scroll-behavior: smooth到可滚动元素。

html {
  scroll-behavior: smooth;
}
#scrollable {
  overflow:auto;
}
#firstDiv {
  background-color: green;
  height: 700px
}
#secondDiv {
  background-color: yellow;
  height: 200px;
}
#thirdDiv {
  background-color: blue;
  height: 500px;
}
<a href="#firstDiv">firstDiv</a>
<a href="#secondDiv">SecondDiv</a>
<a href="#thirdDiv">thirdDiv</a>
<div id="scrollable">
  <div id="firstDiv"></div>
  <div id="secondDiv"></div>
  <div id="thirdDiv"></div>
</div>

对于您的代码,只需更改此行 <a class = "menu__link" data-id=${id}">${name}</a>

至此<a class="menu__link" href="#${id}">${name}</a>

关于javascript - 使用 JavaScript 滚动功能导航到适当的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69659080/

相关文章:

javascript - $http post 请求不起作用并发送 "Possible unhandled rejection"错误

javascript - 用js生成动态站点地图?

javascript - 使用顺序 for 循环解析多链 Promise

javascript - 获取此 javascript 中的标签

jquery滚动到表单输入

Jquery ScrollTo 缓动

javascript - 从 jquery 中的 scrollTo 动画中排除特定#

javascript - 返回 tr 标签的 "value"属性

jquery - 单击按钮时保留页面,新页面加载后启动平滑滚动到指定位置

javascript - 使用 jQuery 查找当前可见元素并更新导航