js 动画滚动到指定位置 ES6

余生长醉 提交于 2019-11-27 09:40:49

### 开始 ###

写一个自动滚动过度到指定位置的一个函数 通过Class进行封装

/**
  * 滚动动画过度
  * @param {Object} position 定位(只支持Y轴)
  * @param {Number} delay 单位毫秒 default 200
  * @param {Number} speed 单位毫秒 default 10
  * 误差:滚动距离越短误差越小
  */
export class AnimationScrollTop {
  constructor (position, delay = 200, speed = 10) {
    this.position = position
    this.delay = delay
    this.speed = speed
    this.step = this.delay / this.speed
    this.dimension = this.position.y / this.step
    this.thisTop = window.pageYOffset
    this.delayt = this.thisTop
    this.upOrDown = this.thisTop > this.position.y
    this.delays = null
    // 初始化
    this.init()
  }
  init () {
    this.delays = setInterval(() => {
      if (!this.upOrDown) {
        if (this.delayt >= this.position.y) {
          clearInterval(this.delays)
        }
        this.delayt += this.dimension
      } else {
        if (this.delayt <= this.position.y) {
          clearInterval(this.delays)
        }
        this.delayt -= this.dimension
      }
      window.scrollTo(this.position.x, this.delayt)
    }, this.speed)
  }
}

使用方式

new AnimationScrollTop({x: 0, y: 500})

### END ###

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!