在 Hotwire Turbo 链接跳转时保持窗口滚动位置

Rei
·

GeekNote 使用了 Hotwire 的 Turbo,有些地方需要用到 Tab 导航。我希望在切换 Tab 的时候保持页面滚动的位置,避免页面跳动。

经过搜索,发现 Hotwire 有个 Issus 提出了这个需求,然后维护者给了官方的实现思路:https://github.com/hotwired/turbo/issues/37#issuecomment-751523976 。这个实现对当前版本有些问题,根据后面的回复我找到了适合当前版本的实现。

只需加入一段 js:

let scrollTop = 0

window.addEventListener("turbo:click", ({ target }) => {
  if (target.hasAttribute("data-turbo-preserve-scroll")) {
    scrollTop = document.scrollingElement.scrollTop
  }
})

window.addEventListener("turbo:render", () => {
  if (scrollTop) {
    document.scrollingElement.scrollTo(0, scrollTop)
    Turbo.navigator.currentVisit.scrolled = true
  }

  scrollTop = 0
})

然后在需要保持位置的链接上加上 data-turbo-preserve-scroll 属性,例如:

<div class="tab">
  <a href="..." class="tab__item" data-turbo-preserve-scroll>item</a>
</div>

这样在通过这个链接跳转页面后,页面会保持当前的滚动位置。

2
1
社区准则 博客 联系 社区 状态
主题