UNPKG

captain-ui

Version:

有赞vue wap业务组件库

90 lines (68 loc) 2.24 kB
"use strict"; exports.__esModule = true; exports.default = animate; /** * 动画库 * * @export * @param {DOMElement} el - dom挂载元素 * @param {Object} options - 参数 * @param {Object} options.source - 运动初始状态 * @param {Object} options.target - 运动结束状态 * @param {number} options.number - 运动持续时间, 单位毫秒 * @param {Function} options.callback - 运动完成回调函数 */ function animate(el, options) { var isFunction = function isFunction(obj) { return typeof obj === 'function'; }; var isNumber = function isNumber(obj) { return typeof obj === 'number'; }; var isObject = function isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; }; // window.requestAnimationFrame的兼容处理 if (!window.requestAnimationFrame) { window.requestAnimationFrame = function (fn) { setTimeout(fn, 17); }; } // 动画计算要的几个变量 var start = 0; var diff = {}; // during根据设置的总时间计算 var during = Math.ceil(options.duration / 17); // 匀速运动算法 var Linear = function Linear(t, b, c, d) { return c * t / d + b; }; // diff函数 var diffValue = function diffValue(start, from, to, during) { if (isNumber(from) && isNumber(to)) { return to - from; } if (isObject(from) && isObject(to)) { for (var i in from) { if (to.hasOwnProperty(i)) { diff[i] = Linear(start, from[i], to[i] - from[i], during); } } if (isNumber(diff.x)) { diff.transform = "translate3d(" + diff.x + "px, " + diff.y + "px, 0)"; delete diff.x; delete diff.y; } return diff; } }; // 运动 var step = function step() { start++; // 当前的运动位置 var properties = diffValue(start, options.from, options.to, during); // 如果还没有运动到位,继续 if (start <= during) { for (var i in properties) { el.style[i] = properties[i]; } window.requestAnimationFrame(step); } else { // 动画结束,这里可以插入回调... isFunction(options.callback) && options.callback(); } }; // 开始执行动画 step(); }