描述:通过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()
}
}
/* 小弟初次记录搬砖历程,如有不对之处,欢迎大佬多多指教 */