锚点滚动定位

在项目中会使用到点击树节点让左侧列表滚动定位到指定位置

1.使用scrollIntoView( )进行定位(注:如果页面中存在fixed布局,不推荐使用,可能会出现页面整体向上的问题)

  此方法需要给每一个dom设置id,在左侧树点击拿到对应右侧dom的id,

if (data.Id) {//data.Id判断id是否存在
        if (document.getElementById(data.Id)) {//判断dom是否存在
          document.getElementById(data.layerGeoServeId).scrollIntoView();//定位
        }
      }

  此方法需要保证id当前页面id唯一,因为使用的是document.getElmentById的方法。

2.使用scroll( )高度计算来定位(推荐)

let element = document.getElementById('list');//获取列表所在dom
  let height = document.getElementById(id).offsetTop-250; //计算需要向上移动的距离
  element.scroll({
    top: height, //向上移动多少
    behavior: 'smooth', // 平滑移动
  });

这个也需要给dom设置指定的id,来进行滚动,高度计算可以自己来测试

posted @ 2022-08-08 15:12  奔跑的哈密瓜  阅读(410)  评论(0编辑  收藏  举报