浏览器滚动恢复属性History.scrollRestoration

最近在阅读React新版官网的代码时,发现在_app.tsx中有这样一段代码。

useEffect(() => {
  // Taken from StackOverflow. Trying to detect both Safari desktop and mobile.
  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  if (isSafari) {
    // This is kind of a lie.
    // We still rely on the manual Next.js scrollRestoration logic.
    // However, we *also* don't want Safari grey screen during the back swipe gesture.
    // Seems like it doesn't hurt to enable auto restore *and* Next.js logic at the same time.
    history.scrollRestoration = 'auto';
  } else {
    // For other browsers, let Next.js set scrollRestoration to 'manual'.
    // It seems to work better for Chrome and Firefox which don't animate the back swipe.
  }
}, []);

这里用到了我没有接触过的一个属性History.scrollRestoration,发现这个属性是用来控制页面刷新或者返回后是否滚动到原来的位置。

MDN文档

属性的值:

  1. auto 将恢复用户已滚动到的页面上的位置。
  2. manual 未还原页上的位置。用户必须手动滚动到该位置。

在mdn文档中没有看到auto是默认值,但是自己手动验证以及在google blog 中提到:

The good news is, however, that there’s a potential fix: history.scrollRestoration. It takes two string values: auto, which keeps everything as it is today (and is its default value), and manual, which means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app’s history.

所以auto确实是默认值没错。

举例

  1. 如果history.scrollRestoration = ‘auto’; 自动回到原有位置。

  2. 如果history.scrollRestoration = ‘manual’; 回到顶部。

在react.org/beta(新版官网)中为什么要使用manul

这是因为这个项目用的next.js,涉及到ssr,可能出现页面还没渲染完就滚动到了之前的位置。(待补充例子。)
可以看一下这篇文档Next.js 中怎么保持页面的滚动位置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值