实现说明
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);