代码如下:
代码如下:
function animate(options){
this.from = options.from;//如果没有from,就计算出from
this.to = options.to || {};
this.onStart = options.onStart || empty;//以下是一些回调函数,就不采用事件机制了
this.onStop = options.onStop || empty;
this.onAnimate = options.onAnimate || empty;
this.onContinue = options.onContinue || empty;
this.onPause = options.onPause || empty;
var element = options.element;
var duration = options.duration || 300;//变化的总时长,单位是ms
var pending = false;//是不是已经暂停了,如果还木有开始的话,该值也是true
var timer = null;
var mixin = options.mix;
var defaultState = this.from || getState(element, this.to);//原始的数据
var thiz = this;
//获取最初始的样式
function getState(ele, targetStyles){
var obj = {};
var i = 0;
for (var p in targetStyles)
{
i++;
obj[p] = parseFloat(mixin.getStyle(ele, p));
}
if(i == 0){
return null;
}
return obj;
}
function empty(){}
function animate(from, to, elapse){
var startTime = (new Date).getTime() + (elapse ? - elapse : 0);//如果有第三个参数,证明是从一个暂停开始的,那么就设置startTime为当前时间减去暂定时已经逝去的时间,如果只有两个参数,那么逝去时间就是0
timer = setInterval(function(){
var endTime = (new Date).getTime();
if(endTime - startTime < duration){
thiz.onAnimate();
currentElapse = endTime - startTime;
for(var p in from){
if(from.hasOwnProperty(p)){
var currentPropertyStyle = mixin.compute(currentElapse, from[p], to[p]-from[p], duration);
mixin.setStyle(element, p, currentPropertyStyle);
}
}
}
else{
thiz.stop(thiz.to);
}
}, 16);
}
this.start = function(){
if(pending){
this.resume();
}
else{
this.onStart();
animate(defaultState, this.to);
}
}
this.stop = function(){
clearInterval(timer);
var styles = this.to;
for(var p in styles){
if(styles.hasOwnProperty(p)){
mixin.setStyle(element, p, styles[p]);
}
}
this.onStop();
}
this.pause = function(){
clearInterval(timer);
pending = true;
this.onPause();
}
this.resume = function(){
pending = false;
this.onContinue();
animate(defaultState, this.to, currentElapse);
}
}
代码如下:
var mixinT = {
getStyle:baidu.dom.getStyle,
setStyle:baidu.dom.setStyle,
compute:function(t, b, c, d){
//return t*c/d + b;
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
}
};
var mixinJQ = {
getStyle:function(ele, styleName){
return $(ele).css(styleName);
},
setStyle:function(ele, styleName, styleValue){
$(ele).css(styleName, styleValue);
},
compute:function(t, b, c, d){
return b+ t*c/d;
}
};
var an = new animate({
element:document.getElementById('anim'),
//from:{'width':100, 'height':100, left:0, top:30},
to:{left:500},
mix:mixinT,
duration:2000
});
if(/demo=1/.test(location.search)){
var demolink = baidu.g('demolink');
demolink.href= 'animate.html';
demolink.innerHTML = 'back';
an.start();
setTimeout(function(){
an.pause();
resume();
}, 1200);
function resume(){
setTimeout(function(){an.resume()}, 1000);
}
}