【问题标题】:Next.js - Disable jump to anchor when using router.push()Next.js - 使用 router.push() 时禁用跳转到锚点
【发布时间】:2021-07-30 15:49:12
【问题描述】:

使用next10.2,每次我们将带有哈希的URL推送到路由器时,next都会跳转到锚元素。

import {useRouter} from 'next/router'

router.push('/contact#about-us');

如果我禁用scroll,也会发生这种情况

router.push('/contact#about-us', undefined, { scroll: false });

我想平滑滚动到锚元素,而不是将其委托给 next.js。

import React from 'react'
import {useRouter} from 'next/router'
import PropTypes from "prop-types";

const LinkSmoothScroll = ({href, className, children}) => {
  const router = useRouter()

  const linkClicked = (e) => {
    e.preventDefault();

    router
      .push(href, undefined, {scroll: false})
      .then(() => {
        const el = document.getElementById(href);

        if ( typeof el !== "undefined" ) {
          // Since header element is fixed, and document height is not being
          // affected by fixed/absolute elements, we need to consider this
          // on the margin to be applied.
          const headerHeight = document.getElementById("nav-header")?.scrollHeight || 0;
          const scrollTopY = el.top + window.scrollY - headerHeight;

          window.scrollTo({
            left: el.left,
            top: scrollTopY,
            behavior: 'smooth'
          });
        }

      });
  }

  return (
    <a href={href} className={className} onClick={linkClicked}>{children}</a>
  )
}

LinkSmoothScroll.propTypes = {
  href: PropTypes.any,
  children: PropTypes.string,
  className: PropTypes.string
}

export default LinkSmoothScroll;

我没有找到任何方法来禁用此行为,也没有找到避免它的调整。

【问题讨论】:

  • 那是因为#about-us,您将用户定向到ID为about-us的元素
  • @DedaDev 期望的行为是跳转到contact 页面,但preventDefault 在跳转到元素时,手动处理(使用平滑滚动)。跨度>
  • 你是如何手动处理滚动的?你不能阻止那里的默认行为吗?
  • @juliomalves 你说的not prevent the default behavior 是什么意思?我在preventDefault() 之后对元素中的点击事件执行router.push()。一旦我删除 router.push() 我就没有跳跃效果
  • 跳转到锚点的行为并不是 Next.js 特有的,它的发生是因为您在导航路径中添加了一个锚点(在这种情况下,当您调用 router.push() 时)。你提到你想手动处理跳转 - 你在哪里做?

标签: javascript reactjs next.js


【解决方案1】:

一些想法。

#1 - 使用 CSS

html {
  scroll-behavior: smooth;
}

#2 - 不要在哈希中使用目标 ID

通过在哈希中为 ID 添加前缀来避免浏览器行为,这样就无法在页面中找到匹配的元素(#about-us 变为 #prefix-about-us)。然后在导航上解析它并用JS滚动到它。

在我看来,这两种方法都不是很好,如果可能,最好保留默认行为。

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 2012-12-13
    • 2019-02-01
    • 2011-04-09
    • 2015-01-21
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多