• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ZiWeiter
博客园    首页    新随笔    联系   管理    订阅  订阅

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)
  }
}

使用方式

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

### END ###

posted @ 2019-08-15 10:54  ZiWeiter  阅读(2600)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3