取消页面再次加载后的滚动位置

这篇文章发布于

DeathGhost 编辑, 归类于 javascript » 当前评论 0 条。

时常web页面中会用到或看到:history.forward()、history.back()或history.go(1)之类的操作,下面了解一个history另外一个属性 —— scrollRestoration 滚动恢复。

浏览web页面信息时我们都会发现这么个细节,当浏览到某一片段时,因其他原因暂时离开当前页面、后退、前进或刷新重新加载(F5)此页面 ,浏览器会默认恢复滚动到上次浏览的位置,当然这也是最佳体验设计。

history.scrollRestoration取消页面再次加载后的滚动位置 防止自动恢复页面位置
history.scrollRestoration取消页面再次加载后的滚动位置 防止自动恢复页面位置

有些情况下,不想让浏览器定位到上次访问的位置,该如何处理?

第一时间想到的就是页面加载完毕设置scrollTop0即可。

element.scrollTop = intValue;

今天介绍的不是它,而是一个History API里的scrollRestoration。可以浏览器控制台输出。

History {length: 2, scrollRestoration: 'auto', state: {…}}

History 的接口——滚动恢复属性允许 web 应用程序在历史导航上显式地设置默认滚动恢复行为。

scrollRestoration语法

const scrollRestore = history.scrollRestoration

scrollRestoration属性值

auto 默认值:将恢复用户已滚动到的页面上的位置。

manual 未还原页面上的滚动位置。必须手动滚动到该位置(防止自动恢复页面位置)。

所以只需要执行history.scrollRestoration属性值为manual即可取消上次记录的滚动位置。

if (history.scrollRestoration) {
  history.scrollRestoration = 'manual';
}

相比scrollTop处理方式,我觉得history.scrollRestoration方式更为友好。


history scrollRestoration history.scrollRestoration scrollTop 滚动 滚动位置 恢复滚动位置 防止自动恢复页面位置 页面刷新滚动 返回

上一篇:

下一篇: