2

如何优雅地取消页面滚动恢复行为?

 1 year ago
source link: https://www.fly63.com/article/detial/12426
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

通常我们在浏览web页面时,当浏览到某个位置跳去了其它页面浏览后再回到开始时的那个页面时,浏览器会帮我们重新定位到我们离开页面时的位置,对于绝大多数场景来说,这确实是一个非常好的体验设计!但有时候我们往往不想这样,这个时候我们是不是通常会使用scrollTop来解决这一问题,今天我们再来介绍一种更佳优雅的方法scrollRestoration。

history

我们平常在web页面中会用到:history.forward()、history.back()或history.go(1)之类的操作,但history还有另外一个神奇的属性 —— 「scrollRestoration 滚动恢复」

scrollRestoration

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

语法

const scrollRestore = history.scrollRestoration
  • auto:将恢复用户已滚动到的页面上的位置。(默认值)
  • manual:未还原页上的位置。用户必须手动滚动到该位置。

文档上虽然并没有明确说明谁是默认值,但从我们的平常使用体验上来将,这个默认值应该就是auto。当然我们也可以自行验证,找一个自己的页面在浏览器打开,然后在控制台输入history

642bc05ea7d0d.jpg

这里我们就能看到history.scrollRestoration的默认值就是auto

所以也就是说如果浏览器支持history.scrollRestoration并且值为auto则会默认的滚动恢复行为,如果设置为manual则可以取消滚动恢复行为

window.history.scrollRestoration && (window.history.scrollRestoration = 'auto')

这种方式相对于我们常用的scrollTop要更加的优雅。

642bc0641415d.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK