JavaScript链式运动框架与案例

链式运动的框架

//链式运动,实现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。鼠标移出后,元素的各项属性开始逆向运动回到初始值。

javascript链式运动

完整的代码: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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值