【问题标题】:Scroll position on initial page load does not go to hash/anchor position when directly accessed the URL in nuxt app直接访问 nuxt 应用程序中的 URL 时,初始页面加载时的滚动位置不会转到哈希/锚点位置
【发布时间】:2020-06-20 07:33:53
【问题描述】:

我的 nuxt.js 应用中有一些锚链接。它工作正常。 说,当我尝试通过带有 id 属性的 navbar/ 标签访问页面的一部分时,它工作正常。

<a href="#anchor">Scroll to anchor</a> - 有效
<nuxt-link to="#anchor">Scroll to anchor</a> - 也有效

但是当我尝试通过 URL 直接访问相同的 - xxx.com/test#anchor 时,它会进入测试页面,但不会滚动到 #anchor div。

我尝试过的一些解决方法是,

<nuxt-link :to="{path: '/', hash: 'anchor'}">link</nuxt-link>

我也在 nuxt-config 中更改了支持此功能的滚动行为,

scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash
      }
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  },

这在加载时不起作用。我发现已经提出了相同类型的问题,但仍然存在,

https://github.com/nuxt/nuxt.js/pull/6922

https://github.com/nuxt/nuxt.js/issues/6921

【问题讨论】:

  • 我使用的nuxt版本是2.11.0

标签: javascript nuxt.js


【解决方案1】:

有一个类似的问题,这个黑客解决了它。

  mounted() {
    if (this.$route.hash) {
      let hash = this.$route.hash
      hash = hash.replace('#', '')
      const anchor = document.getElementById(hash)

      if (anchor) {
        window.scrollTo({
          top: anchor.getBoundingClientRect().top + window.scrollY,
        })
      }
    }
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2015-05-05
    相关资源
    最近更新 更多