js 動畫滾動到指定位置 ES6

### 開始 ###函數

寫一個自動滾動過分到指定位置的一個函數 經過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)
  }
}

使用方式this

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

### END ###spa

相關文章
相關標籤/搜索