vuvivian's blog

越努力,越幸运.

日常小结/获取元素定位位置并实现滚动条定位

vuvivian's Avatar 2020-04-29

  1. 1. 找到出现滚动条的盒子容器
  2. 2. 使用getBoundingClientRect获取要定位元素的位置
  3. 3. 使用scrollTo定位滚动条位置
  4. 4. 如果持续往下定位的话需要在定位前清一下滚动条位置

找到出现滚动条的盒子容器

使用getBoundingClientRect获取要定位元素的位置

document.getElementById(this.activeName).getBoundingClientRect()

使用scrollTo定位滚动条位置

document.querySelector(‘.std-menu-container’).scrollTo(0, document.getElementById(this.activeName).getBoundingClientRect().y - 121);

如果持续往下定位的话需要在定位前清一下滚动条位置

document.querySelector(‘.std-menu-container’).scrollTo(0, 0);

本文最后更新于 天前,文中所描述的信息可能已发生改变