30 NextJS: 如何在点击链接,到达 section 的时候,往上滚动一定数值的像素?

我现在在写的一个 NextJS project,里面有一个 navigation bar,通过点击对应的链接,会进入对应的页面。

不过有几个链接是到达页面内的 section,由于我的 navigation bar 是固定在页面上方的,如果直接到达 section,该 section 的最上方的部分会被固定的 navigation bar 挡住,所以我希望到达 section 之后,还能再往上滚动 100-200 个像素, 这样才能完整显示 section 内容。

我使用了 `

const scrollSection = useRef<HTMLElement | null>(null)

const handleNavLinkClick = () => {
    if (scrollSection.current) {
        const scrollOptions: ScrollIntoViewOptions = {
            behavior: 'smooth',
            block: 'start',
            inline: 'nearest',
        }
        scrollSection.current.scrollIntoView(scrollOptions)
        window.scrollBy(0, -300)
    }
}        。。。

< NavLink href="/page1#section1" onClick={handleNavLinkClick}>Section name< /NavLink> 。。。

    但似乎没有效果。
请先 登录 后评论

1 个回答

Yiming
请先 登录 后评论
  • 2 关注
  • 0 收藏,298 浏览
  • NPC.李括 提出于 2024-03-14 13:32