scrollIntoView 导致页面整体上移

555 阅读1分钟

背景

需要针对列表做指定滚动功能,比如通过链接上携带参数进行商品定位,列表数据通过请求后端获取,原始处理方法是使用 hmtl scrollIntoView API实现,结果发现页面整体会向上滚动,也就是body偏离了;

原来的解决方法

const anchorElement = document.getElementById(goods_id);
if (anchorElement) {
    anchorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

改进后的解决方法

  const container = document.getElementById('contain');
  const target = document.getElementById(goods_id);
  interactiveNpcId.current = '';
  if (target) {
    const targetPosition = target.offsetTop;
    const containerScrollPosition = targetPosition - container.offsetTop;
    container.scrollTo({
      top: containerScrollPosition,
      behavior: 'smooth',
    })
  }

备注

因为数据是从接口请求到后再渲染至页面,所以不管使用哪种方式,都在请求响应后加一定的延迟(setTimeout)进行执行保证能正常获取到dom节点进行滚动,我们的数据比较少,我给的100ms延迟实测OK