首页 > 代码库 > JS动画之链式运动与同时运动
JS动画之链式运动与同时运动
一、链式运动
所谓的链式运动,就是在平常的动画运动函数最后在传入一个参数,当第一个动画运动运动完后,检测一下有没有继续传入的参数,如果有的话就继续运行这个参数,这样重复下去就可以完成一套链式运动
var Li=document.getElementById("li1");
Li.onmouseover=function(){
startMove(Li,"width",400,function(){
startMove(Li,"height",400,function(){
startMove(Li,"opacity",100);
});
});
}
Li.onmouseout=function(){
startMove(Li,"opacity",30,function(){
startMove(Li,"height",100,function(){
startMove(Li,"width",200);
});
});
}
function startMove(obj, attr, iTarget, fn) { //添加一个回调函数fn
clearInterval(obj.timer); //1.2+++
obj.timer = setInterval(function () { //1.2+++
var icur = null;
//1.判断类型
if (attr == ‘opacity‘) {
icur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
} else {
icur = parseInt(getStyle(obj, attr));
} //2.算速度
var speed = (iTarget - icur) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
//3.检测停止
if (icur == iTarget) {
clearInterval(obj.timer);
if (fn) { //判断是否存在回调函数,并调用
fn();
}
} else {
if (attr == ‘opacity‘) {
obj.style.filter = ‘alpha(opacity:‘ + (icur + speed) + ‘)‘;
obj.style.opacity = (icur + speed) / 100;
} else {
obj.style[attr] = icur + speed + ‘px‘;
}
}
}, 30);
}
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, false) [attr];
}
}
二、同时运动:最终封装的‘完美移动框架‘
function startMove(obj, json, fn) {
var flag = true; //标志所有运动是否到达目标值
clearInterval(obj.timer);
obj.timer = setInterval(function () {
for (var attr in json) {
var curr = 0;
//判断是否为透明度
if (attr == ‘opacity‘) {
curr = Math.round(parseFloat(getStyle(obj, attr)) * 100);
} else {
curr = parseInt(getStyle(obj, attr));
} //移动速度处理
var speed = 0;
speed = (json[attr] - curr) / 10;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (curr != json[attr]) {
flag = false;
}
if (attr == ‘opacity‘) {
obj.style.filter = ‘alpha(opacity:‘ + (curr + speed) + ‘)‘;
obj.style.opacity = (curr + speed) / 100;
} else {
obj.style[attr] = curr + speed + ‘px‘;
}
}
if (flag) {
clearInterval(obj.timer);
if (fn) {
fu();
}
}
}, 30);
}//取样式
function getStyle(obj, attr) {
if (obj.currentStyle) { //IE取样式
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, false) [attr];
}
}
JS动画之链式运动与同时运动