首页 > 技术文章 > 多物体运动

lzzhuany 2015-05-28 18:15 原文

解决了多物体运动定时器之间的干扰,在每个物体上都定义一个定时器,关闭定时器是只关闭自身的定时器,物体就可以独立运动互补干扰了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
div{width:100px; height:50px; background:#F00; margin:10px;}


</style>
<script>
window.onload=function()
{
	var aDiv=document.getElementsByTagName('div');
	
	for(var i=0;i<aDiv.length;i++)//为每个div都添加一个事件
	{
		aDiv.timer=null;//为每个div添加一个属性,用来存储定时器
		aDiv[i].onmouseover=function()
		{
			onmove(this,400);//那个div调用函数,就传入该div对象,改变该div的属性
		}
		aDiv[i].onmouseout=function()
		{
			onmove(this,50);
		}
	}
	
}
var timer;
	
function onmove(obj,iTarget)
{
	clearInterval(obj.timer);//关闭调用这个函数的定时器,多个物体同时调用,定时器之间不影响
	obj.timer=setInterval(function()//设置定时器,用于在运动中改变宽度的值
	{
		var speed=(iTarget-obj.offsetWidth)/6;//缓冲运动
		speed=speed>0?Math.ceil(speed):Math.floor(speed);//对速度上下取整,才能到达准确的指定位置
		
		if(obj.offsetWidth==iTarget)
		{
			clearInterval(obj.timer);
		}
		else
		{
			obj.style.width=obj.offsetWidth+speed+'px';//让调用此函数的对象宽度改变
		}
	},30);
}
</script>
</head>

<body>
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
</body>
</html>

 

推荐阅读