JS运动函数 move.js
function getStyle(obj, attr) {
if (obj.getcurrentStyle) {
return obj.currentStyle[attr];
}
else {
return getComputedStyle(obj, false)[attr];
}
}
//完美运动框架
//startMove(obj, {attr1:itarget1,attr2:itarget2},fn);
fn()为回调函数,在运动结束之后执行fn,fn可以为另一个startMove
function startMove(obj, json, fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var flat = true; //是否所有的都到达目标值的标识,也是运动是否结束的标识。
for (var attr in json) {
//获取当前的值
var icur = 0;
if (attr == 'opacity') {
icur = Math.round((getStyle(obj, attr)) * 100);
}
else {
icur = parseInt(getStyle(obj, attr));
}
//计算速度
var speed = (json[attr] - icur) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (icur != json[attr]) {
flag = false;//如果不是所有的都到达目标值,运动不结束。
}
if (attr == 'opacity') {
obj.style.filter = 'alpha(opacity:' + (icur + speed) + ')';
obj.style.opacity = (icur + speed) / 100;
}
else {
obj.style[attr] = icur + speed + 'px';
}
}
if (flag) {
clearInterval(obj.timer);
if (fn) {
fn();
}
}
}, 30);
}
html中应用
<script src="Scripts/move.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function () {
var Li = document.getElementById("li1");
Li.onmouseover = function () {
startMove(Li, { width: 400, height: 200 });
};
Li.onmouseout = function () {
startMove(Li, { width: 200, height: 100 });
};
};
</script>