← 中文资源

简体中文版本

history.scrollRestoration 保持刷新位置稳定

scrollRestoration 决定浏览器是否在刷新/后退时恢复滚动位置:长列表路由切 manual 由自己接管,详情页切 auto 交还浏览器;它是浏览器行为不是页面状态,每个路由启动时都要重新设置。

阅读英文原文

实现说明

history.scrollRestoration 保持刷新位置稳定的核心是函数 openListView、openDetailView。

使用要点

  • 跑完文件,输出里会留下标记——default mode:、list view:、detail view:。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 openListView、openDetailView。

入口签名:function openListView()

核心语句

const initial = history.scrollRestoration;
history.scrollRestoration = 'manual';
history.scrollRestoration = initial;

代码示例

// auto (default): the browser restores scroll on reload/back.
// manual: your code decides where the viewport lands.
const initial = history.scrollRestoration;
console.log('default mode:', initial);

// Long list views opt out of the jump-to-top behavior.
function openListView() {
  history.scrollRestoration = 'manual';
  console.log('list view:', history.scrollRestoration);
}

// Detail views hand control back to the browser.
function openDetailView() {
  history.scrollRestoration = 'auto';
  console.log('detail view:', history.scrollRestoration);
}

openListView();
openDetailView();

// The mode survives reloads as a browser behavior, not as page state —
// each route must set it again while booting.
history.scrollRestoration = initial;
console.log('restored:', history.scrollRestoration === initial);