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

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

Author: DeathGhost
Published: 2022-06-11 12:40:44
Category: javascript
Canonical: https://www.deathghost.cn/article/javascript/109
Keywords: history, scrollRestoration, history.scrollRestoration, scrollTop, 滚动, 滚动位置, 恢复滚动位置, 防止自动恢复页面位置, 页面刷新滚动, 返回

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

![history.scrollRestoration取消页面再次加载后的滚动位置 防止自动恢复页面位置](https://www.deathghost.cn/public/upload/article/2022/06/11/1654924247527504.jpg)

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

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

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

element.scrollTop = intValue;
今天介绍的不是它，而是一个History API里的scrollRestoration。可以浏览器控制台输出。

History {length: 2, scrollRestoration: 'auto', state: {&hellip;}}
History 的接口&mdash;&mdash;滚动恢复属性允许 web 应用程序在历史导航上显式地设置默认滚动恢复行为。

## scrollRestoration语法

const scrollRestore = history.scrollRestoration

## scrollRestoration属性值

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

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

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

if (history.scrollRestoration) {
  history.scrollRestoration = 'manual';
}
相比scrollTop处理方式，我觉得history.scrollRestoration方式更为友好。

## Related

- Previous: [EyeDropper API - 启用浏览器吸管工具获取屏幕任意目标元素HEX色值](https://www.deathghost.cn/article/javascript/105)
- Next: [JS原生的深拷贝API structuredClone()](https://www.deathghost.cn/article/javascript/120)
