滚动条恢复行为

2020-08-11  本文已影响0人  HelloKang

问题

Vue路由跳转,目标页面会继承起始页面的滚动条的位置。

history.scrollRestoration

有这样一个 API 可以修改浏览器的滚动恢复行为,它有两个值:
auto
将恢复用户已滚动到的页面上的位置。
manual
未还原页上的位置。用户必须手动滚动到该位置。

使用

const scrollRestoration = history.scrollRestoration
if (scrollRestoration === 'manual') {
  console.log('未还原页面上的位置,用户将需要手动滚动');
}
scrollRestoration = 'auto' // 恢复页面滚动恢复行为

兼容性如下

image.png

window.scrollTo

实际使用发现 history.scrollRestoration 在 Vue 路由跳转上使用并不好使
只好在目标页面增加window.scrollTo(0, 0)手动将页面滚动的顶部。

上一篇下一篇

猜你喜欢

热点阅读