Let's take a look at the previous code of motion and whether it supports the motion of multiple objects.
Copy Code code as follows:
<style type= "Text/css" >
div {
width:100px;
height:50px;
background:red;
margin:10px;
}
</style>
Copy Code code as follows:
<body>
<div></div>
<div></div>
<div></div>
</body>
Here's the JavaScript code:
Copy Code code 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, he is running normally. But if you move to a second or third Div now, a bug will appear.
Image what is the reason for this? Looking at the picture shows that there is no movement to complete. Actually, it is.
The whole program on a timer, such as the first Div started moving, the second Div mouse moved into the previous timer was killed, then nature is 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, when the timer is closed when the timer on the object, open is also the timer on the object
Then they can run completely undisturbed.
Look at the modified JavaScript code:
Copy Code code 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; To save a timer as a property 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>
So the program is no problem, can support the movement of multiple objects.