天天看点

vue滚动条缓慢移动到某个位置

 需求:需要滚动条缓慢移动到某个位置

scrollAnimation(currentY, targetY) {
      // 获取当前位置方法
      // 计算需要移动的距离 
      let needScrollTop = targetY - currentY
      let _currentY = currentY
      setTimeout(() => {
        // 一次调用滑动帧数,每次调用会不一样
        const dist = Math.ceil(needScrollTop / 10)
        _currentY += dist
        window.scrollTo(_currentY, currentY)
       // 如果移动幅度小于十个像素,直接移动,否则递归调用,实现动画效果
        if (needScrollTop > 10 || needScrollTop < -10) {
          this.scrollAnimation(_currentY, targetY)
        } else {
          window.scrollTo(_currentY, targetY)
        }
 }, 1)
           

执行的地方:

比如移动到顶部

const currentY = document.documentElement.scrollTop || document.body.scrollTop        
 this.scrollAnimation(currentY, 0)
           

比如移动到底部(页面容器id为page)

const currentY = document.documentElement.scrollTop || document.body.scrollTop   
const bottomY = document.getElementById("page").clientHeight     
this.scrollAnimation(currentY, bottomY )
           
vue