1.實現鏈式運動的一個關鍵是利用回調函數
2.下面是一個比較實用的框架,但不是完美的,特別是在同時運動上,還需要用到json
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];
}
}`
3.完美型的運動框架
`function startMove(obj,json,fn){
clearInterval(obj.timer);//清除定時器,避免重復生成多個定時器
obj.timer=setInterval(function(){
var flag=true;//假設剛開始時所有運動都已完成
for (var attr in json) {//遍歷json
var icur=null;
//1.判斷類型
if(attr=='opacity'){
icur=Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
icur=parseInt(getStyle(obj,attr));
}
//2.算速度
var speed=(json[attr]-icur)/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
//3.檢測停止
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);
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}