Implementation of Javascript multi-object motion and javascript Object Motion
Let's take a look at the previous motion code to see if multi-object motion is supported.
Copy codeThe Code is as follows:
<Style type = "text/css">
Div {
Width: 100px;
Height: 50px;
Background: red;
Margin: 10px;
}
</Style>
Copy codeThe Code is as follows:
<Body>
<Div> </div>
<Div> </div>
<Div> </div>
</Body>
The following is the Javascript code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Window. onload = function (){
Var aDiv = document. getElementsByTagName ('div ');
For (var I = 0; I <aDiv. length; I ++ ){
ADiv [I]. onmouseover = function (){
StartMove (this, 400 );
};
ADiv [I]. onmouseout = function (){
StartMove (this, 100 );
};
}
}
Var timer = null;
Function startMove (obj, iTarget ){
ClearInterval (timer );
Timer = setInterval (function (){
Var speed = (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, it runs normally. However, if you move to the second or third div, a bug occurs.
Why is image? The figure shows that the motion is not completed. In fact,
The whole program has a timer. For example, if the first div starts to be moved, and the second div moves the mouse into the previous timer and is killed, it is naturally stuck there.
So the biggest problem is that the entire program has only one timer. So how can we solve this problem?
Solution:
In fact, it is very simple to add the timer as the attribute of an object, so every object has a timer. When the timer is closed, the timer on the object is closed, and the timer on the object is also enabled.
Therefore, they can run without interfering with each other.
Check the modified Javascript code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Window. onload = function (){
Var aDiv = document. getElementsByTagName ('div ');
For (var I = 0; I <aDiv. length; I ++ ){
ADiv [I]. timer = null; // Save the timer as the attribute of an object.
ADiv [I]. onmouseover = function (){
StartMove (this, 400 );
};
ADiv [I]. onmouseout = function (){
StartMove (this, 100 );
};
}
}
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>
In this way, the program will be able to support the movement of multiple objects.