Javascript 多物体运动的实现
我们先来看下之前的运动的代码,是否支持多物体运动,会出现怎么样的问题。
<styletype="text/css">
div{
width:100px;
height:50px;
background:red;
margin:10px;
}
</style>
<body>
<div></div>
<div></div>
<div></div>
</body>
以下是Javascript代码:
<scripttype="text/javascript">
window.onload=function(){
varaDiv=document.getElementsByTagName('div');
for(vari=0;i<aDiv.length;i++){
aDiv[i].onmouseover=function(){
startMove(this,400);
};
aDiv[i].onmouseout=function(){
startMove(this,100);
};
}
}
vartimer=null;
functionstartMove(obj,iTarget){
clearInterval(timer);
timer=setInterval(function(){
varspeed=(iTarget-obj.offsetWidth)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(obj.offsetWidth==iTarget){
clearInterval(timer);
}else{
obj.style.width=obj.offsetWidth+speed+'px';
}
},30);
}
</script>
此时当鼠标移入到第一个div时,他是正常运行的。但是如果现在又移动到第二个或者第三个div时候就会出现bug。
image这个是什么原因呢?看图可以看出并没有运动完成。实际上是这样的,
整个程序就一个定时器,比如第一个div开始动了,第二个div鼠标移入了前一个定时器就被干掉了,那么自然就卡在那里了。
所以最大的问题就是整个程序就只有一个定时器。那么怎么解决这个问题呢?
解决方案:
其实很简单,把定时器作为一个物体的属性加上,那么每个物体都有一个定时器在,当关闭定时器的时候是关闭物体上的定时器,开也是物体上的定时器
那么他们之间就可以完全互不干扰的运行。
看下修改后的Javascript代码:
<scripttype="text/javascript">
window.onload=function(){
varaDiv=document.getElementsByTagName('div');
for(vari=0;i<aDiv.length;i++){
aDiv[i].timer=null;//把定时器作为一个物体的属性存起来
aDiv[i].onmouseover=function(){
startMove(this,400);
};
aDiv[i].onmouseout=function(){
startMove(this,100);
};
}
}
functionstartMove(obj,iTarget){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
varspeed=(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>
这样程序就没有问题了,能够支持多物体的运动。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下