Js滚动到指定位置

859 阅读1分钟
/**
 * 
 * @param {*} elID 滚动元素
 * @param {*} tar 滚动的目标位置(y轴)
 * @param {*} speed 滚动速度
 */
function scrollToTarget(elID, tar, speed) {
  const scrollToTop = () => {
    let v = document.getElementById(elID)
    const { scrollTop: y, scrollHeight, offsetHeight } = v
    if (Math.abs(y + offsetHeight - scrollHeight) < 15 && tar.start > scrollHeight - offsetHeight) return
    if (Math.abs(y - tar) >= speed / 2) {
       window.requestAnimationFrame(scrollToTop)
       v.scrollBy(0, y > tar? -speed: speed)
    } else {
      v.scrollTo(0, tar)
     }
  }
  scrollToTop()
}

window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行