用了两种方法:第一种是用的jquery,下载一个 jquery-1.7.1.js就好,另一种方法是通过myAnimation.js
嵌入的js路径可能不一样,需要自己调一下。
// myAnimation.js
Tween = {
Linear : function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * t / d + b;
},
Cubic : {
easeIn : function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * (t /= d) * t * t + b;
},
easeOut : function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
return c * (( t = t / d - 1) * t * t + 1) + b;
},
easeInOut : function(initPos, targetPos, currentCount, count) {
var b = initPos, c = targetPos - initPos, t = currentCount, d = count;
if((t /= d / 2) < 1)
return c / 2 * t * t * t + b;
return c / 2 * ((t -= 2) * t * t + 2) + b;
}
}
}
Animation = {
timer : 10,
moveDirection : function(obj, styleName, targetPos, count, Func, callback) {
obj = this.getItself(obj);
count = !!count ? count : 100;
var styleValue = parseInt(obj.offsetTop) || 0;
var currentAnimateFun = Func || Tween.Linear;
var currentCount = 0;
var curInterval = window.setInterval(function() {
if(currentCount > count) {
window.clearInterval(curInterval);
callback();
} else {
currentCount = currentCount + 1;
var tempValue = currentAnimateFun(styleValue, targetPos, currentCount, count);
obj.style[styleName] = tempValue + "px";
}
}, this.timer)
},
movePos : function(obj, targetPos, count, Func) {
obj = this.getItself(obj);
var currentCount = 0;
count = Math.abs(count) || 10;
var elPos = this.getElementPos(obj);
var initPos = {
x : elPos.x,
y : elPos.y
}
Func = Func || Tween.Linear;
var flag = setInterval(function() {
if(currentCount > count) {
clearInterval(flag);
} else {
currentCount++;
var tmpX = Func(initPos.x, targetPos.x, currentCount, count);
var tmpY = Func(initPos.y, targetPos.y, currentCount, count);
obj.style.left = tmpX + "px";
obj.style.top = tmpY + "px";
//清除小数点的误差
if(Math.abs(tmpX - targetPos.x) < 1) {
obj.style.left = targetPos.x + "px";
}
if(Math.abs(tmpY - targetPos.y) < 1) {
obj.style.top = targetPos.y + "px";
}
}
}, this.timer);
},
getElementPos : function(el) {
el = this.getItself(el);
var _x = 0, _y = 0;
do {
_x += el.offsetLeft;
_y += el.offsetTop;
} while (el = el.offsetParent);
return {
x : _x,
y : _y
};
},
getItself : function(id) {
return "string" == typeof id ? document.getElementById(id) : id;
}
}
//main.html
Music Trival