(42)JS运动之多物体框架--多个div变宽

  假设仅仅为div加入一个定时器的话。在多个div变宽的时候会发生故障。可是假设为每一个div加入一个定时器。那么就能够实现多个物体变宽。

注意:在多物体运动的情况下,全部东西不能共用。offsetXXX会跟border冲突导致不能得到想要的结果。在这里能够用getStyle()函数取代。

function getStyle(obj, name)
{
	if(obj.currentStyle)
	{
		return obj.currentStyle[name];
	}
	else
	{
		return getComputedStyle(obj, false)[name];
	}
}

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div{
	100px;
	height:50px;
	background:red;
	margin:10px;
}



</style>
 

<script>

window.onload=function (){
	var aDiv=document.getElementsByTagName('div');
	for(var i=0;i<aDiv.length;i++)
	{	
		aDiv[i].timer=null;//自己定义属性,加一个定时器
		aDiv[i].onmouseover=function ()
		{
			startMove(this,400);
		};
		aDiv[i].onmouseout=function ()
		{
			startMove(this,100);
		};
	}
};

var timer=null;
function startMove(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 ></div> <div ></div> <div ></div> </body> </html>

效果图:



原文地址:https://www.cnblogs.com/gavanwanggw/p/6739424.html