vue的一个简单数字渐变过渡显示实现

描述:通过requestAnimationFrame实现,尽管一个页面多处需要滚动过渡的数字,但可全部放到一个requestAnimationFrame中。从而大大降低性能。下面是js实现示例:

/* roll-num.js */

/**
 * 简单的数字过渡显示
 * @example
 * let roll = new Roll();
 * roll.add(target, { index: 'index', num: 100 });
 * roll.run()
 */
export class Roll {
  rollFuncList = []
  // 可通过constructor在实例对象时,添加全局配置
  // 留空

  _create = function(target, opt) {
    if (!target || !opt.index) {
      console.error('params is error')
      return
    }
    const _config = {
      delay: 0.5, num: 0, index: 'test',
      fromZero: false
    }
    Object.assign(_config, opt)
    target[_config.index] = !_config.fromZero ? target[_config.index] || 0 : 0
    const add = Math.ceil((_config.num - target[_config.index]) / (_config.delay * 60)) || 1
    return function() {
      if (add >= 0 ? target[_config.index] >= _config.num : target[_config.index] <= _config.num) {
        target[_config.index] = _config.num
        return false
      }
      target[_config.index] += add
      return true
    }
  }
  /**
   * 添加滚动对象
   * @param {Object} target 目标对象
   * @param {Object} opt 配置
   * @param {Number} opt.delay 时间(s)
   * @param {String} opt.index 目标对象属性
   * @param {Number} opt.num
   * @param {Number} opt.fromZero
   */
  add = function(target, opt) {
    const tempFunc = this._create(target, opt)
    this.rollFuncList.push(tempFunc)
  }
  /**
   * 开始运行
   */
  run = function() {
    const rollNum = () => {
      this.rollFuncList = this.rollFuncList.filter(cb => cb())
      if (!this.rollFuncList.length) return
      window.requestAnimationFrame(rollNum)
    }
    rollNum()
  }
}

/* 小弟初次记录搬砖历程,如有不对之处,欢迎大佬多多指教 */

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值