move.js 框架
function getStyle(obj, attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj, false)[attr];
}
}
function startMove(obj, attr, iTarget, fn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
//1、取当前的值
var icur = 0;
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)
}JavaScript
鼠标移入先变宽,再变高,然后变透明度
鼠标移出先变透明度,再变高,最后变宽
window.onload = function(){
var Li = document.getElementById('li1');
Li.onmouseover = function(){
startMove(Li, 'width', 400, function(){
startMove(Li, 'height', 200, 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]; } }
链式运动的关键在于:每次运动函数执行完成之后返回相应的dom对象。
好吧,现在还有个新的方法,在原有的基础上增加回调函数。(这种方法在遇到多流程的动画的时候,要写回调地狱。尽量使用1,如果一定要使用2请使用promise)
链式动画,在startMove(obj,attr,iTarget,fn)再加一个fn参数,并在清除动画之后,加入fn方法:if(fn){fn();} 在主页中,在三个参数之后再加入一个参数 startMove(Li,'width',400,function(){ startMove(Li,'height',200,function(){ startMove(Li,'opacity',100); }) })