链式运动的框架
//链式运动,实现div的先变宽,再变高,再改变不透明度
function getStyle(obj,name)
{
if(getComputedStyle(obj,null)[name])
{
return getComputedStyle(obj,null)[name];
//fireFox、chrome
}
else
{
return obj.currentStyle[name];
//IE
}
}
function getByClass(oParent,sClass)
{
var aEle=oParent.getElementsByTagName('*');
var aResult=[];
for(var i=0;i<aEle.length;i++)
{
if(aEle[i].className==sClass)
{
aResult.push(aEle[i]);
}
}
return aResult;
}
function startMove(obj,attr,iTarget,fnEnd)
{
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var cur=0;
if(attr=="opacity")
{
cur=Math.round(parseFloat(getStyle(obj,attr))*100);
}
else
{
cur=parseInt(getStyle(obj,attr));
}
var speed=(iTarget-cur)/30;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(cur==iTarget)
{
clearInterval(obj.timer);
if(fnEnd)fnEnd();
}
else
{
if(attr=="opacity")
{
cur+=speed;
obj.style.fliter='alpha(opacity:'+cur+')';
obj.style.opacity=cur/100;
}
else
{
obj.style[attr]=cur+speed+'px';
}
}
},30)
}
在多物体运动框架的基础上引入了第四个函数参数:fnEnd。当函数抵达目标点后,执行函数fnEnd。
案例:当鼠标移入选定的div元素中后,元素先width运动到300px,抵达300px后height开始运动到300px,height值抵达300px后,opacity的值运动为0.3。鼠标移出后,元素的各项属性开始逆向运动回到初始值。
完整的代码:move.js为引入的运动框架。
<!doctype html>
<html>
<head>
<title>运动</title>
<meta charset="utf-8">
<style>
.div1{width:100px;height:100px;float:left;background:#ccc;margin:5px;}
</style>
<script src='move.js'></script>
<script>
window.onload=function()
{
aDiv=document.getElementsByClassName('div1');
aDiv[1].onmouseover=function()
{
startMove(aDiv[1],'width',300,function(){
startMove(aDiv[1],'height',300,function(){
startMove(aDiv[1],'opacity',30)
})
})
}
aDiv[1].onmouseout=function()
{
startMove(aDiv[1],'opacity',100,function(){
startMove(aDiv[1],'height',100,function(){
startMove(aDiv[1],'width',100)
})
})
}
}
</script>
</head>
<body>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
</body>
</html>