Skip to content

Instantly share code, notes, and snippets.

@zmmbreeze
Created April 27, 2013 10:14
Show Gist options
  • Save zmmbreeze/5472597 to your computer and use it in GitHub Desktop.
Save zmmbreeze/5472597 to your computer and use it in GitHub Desktop.
Javascript simple animation.
/**
* 简易动画函数
*
* @param {HTMLElement} dom 需要执行动画的元素
* @param {Object} props 例如:{'width': 100}.
* @param {function(HTMLElement)=} opt_complete 「可选」动画结束后的回调函数
* @param {Object=} opt_options 配置
* @config {number} interval 动画间隔时间
* @config {function} easing 补间函数
* @config {number} duration 动画耗时
* @config {function(HTMLElement, string, number)} setStyle 设置样式的函数
* @config {function(HTMLElement, string):string} getStyle 获取样式的函数
*
* @return {number} timer 定时器句柄
*/
function anime(dom, props, opt_complete, opt_options) {
// 动画间隔时间
var interval = (opt_options && opt_options.interval) || 20;
// 补间函数
var easing = (opt_options && opt_options.easing) || function(elapsed) {
return elapsed * (2 - elapsed);
};
// 动画执行时间
var duration = (opt_options && opt_options.duration) || 2000;
// 开始时间
var startTime = new Date().getTime();
// CSS属性的结束值
var endProps = props;
// CSS属性的开始值
var startProps = {};
var getStyle = (opt_options && opt_options.getStyle) || function(dom, name) {
return $(dom).css(name);
};
var setStyle = (opt_options && opt_options.setStyle) || function(dom, name, value) {
$(dom).css(name, value);
};
// 初始化
for (var key in props) {
if (props.hasOwnProperty(key)) {
if (typeof endProps[key] === 'string') {
endProps[key] = parseInt(endProps[key], 10);
}
startProps[key] = parseInt(getStyle(dom, key), 10);
}
}
// 执行动画
var timer;
var animate = function() {
var now = new Date().getTime();
// 计算补间百分比
var elapsed = (now - startTime) / duration;
elapsed = elapsed > 1 ? 1 : elapsed;
var value = easing(elapsed);
// 计算更新CSS值
var start;
var end;
for (var key in endProps) {
start = startProps[key];
end = endProps[key];
// 更新CSS
setStyle(dom, key, start + ( end - start ) * value);
}
if (elapsed === 1) {
// END
timer = null;
if (opt_complete) {
opt_complete(dom);
}
} else {
// NEXT ANIMATION
timer = setTimeout(animate, interval);
}
};
animate();
return timer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment