Let's take a look at the code of the previous movement, whether it supports multi-object motion and what the problem will be.
<style type= "Text/css" > { width: 100px; height: 50px; background: Red; margin: 10px; } </style>
< Body > < Div ></ Div > < Div ></ Div > < Div ></ Div > </ Body >
Here's the JavaScript code:
<script type= "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>
When the mouse moves to the first Div, he is running normally. But if you move to the second or third Div now, you'll get a bug.
What is the reason for this? Look at the picture to see that there is no movement done. This is actually the case,
The whole program on a timer, such as the first Div began to move, the second Div mouse moved into the previous timer was killed, then naturally stuck there.
So the biggest problem is that the entire program has only one timer. So how do we solve this problem?
Solution:
In fact, it is very simple, the timer as a property of an object plus, then each object has a timer in, when the timer is closed when the timer is closed on the object, open is also the timer on the object
Then they can run completely non-interfering with each other .
Look at the modified JavaScript code:
<script type= "Text/javascript" >window.onload=function() { varAdiv = document.getElementsByTagName (' div '); for(vari = 0; i < adiv.length; i++) {Adiv[i].timer=NULL;//Save the timer as a property of an objectAdiv[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>
This procedure is no problem and can support the movement of multiple objects.
Next Issue preview:
The next time the movement of any value is updated so that he can support changing the width, height, transparency, etc., the existing frame is not working. In fact, we have begun to gradually improve the framework of the movement.
Please look forward to ~
Javascript Multi-Object motion-progressive parsing of code to make it easy for you to move the principle of motion