前端冷知识:无限滚动触发浏览器回退

187 阅读1分钟

背景:

最近写项目时,出现了一个诡异问题,无限下拉的表格会偶现页面回退,效果如下:

问题出在哪呢?

小原发现如果通过拖拽滚动条, 不会触发浏览器后退, 那么问题应该是出在滚动事件上

浏览器滚动默认行为

小原回想他日常遇到的一些浏览器默认行为, 如:

  1. a标签超链接跳转
  2. InputElement.focus() 元素聚焦默认滚动到对应位置
  3. 子父容器同时存在滚动条, 子容器在滚动到底/顶部时, 同时触发父容器的滚动 这些行为我们都可以通过 preventDefault() 或是 { preventScroll: true } 来解决

看起来 Mac 上滚动触发浏览器回退也是一种浏览器滚动默认行为, 机智的小李一番搜索, 发现了一个叫 overscroll-behavior 的属性, 可以控制浏览器滚动到边界的行为

MDN: We also wanted to get rid of the standard overscroll effects when the contacts are scrolled to the top or bottom (e.g. Chrome on Android refreshes the page when you scroll past the top boundary). This can be prevented by setting overscroll-behavior: none on the <html> element:

果不其然, 在给 html设置 overscroll-behavior: none 后就ok了