Let’s first look at the previous motion code, whether it supports the movement of multiple objects, and what problems will arise.
The code copy is as follows:
<style type="text/css">
div {
width: 100px;
height: 50px;
background: red;
margin: 10px;
}
</style>
The code copy is as follows:
<body>
<div></div>
<div></div>
<div></div>
</body>
Here is the Javascript code:
The code copy 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>
At this time, when the mouse moves into the first div, it is running normally. But if you move to the second or third div now, you will get a bug.
image What is the reason for this? Looking at the picture, you can see that the movement has not been completed. Actually, this is the case,
The whole program is just a timer. For example, the first div starts to move, and the second div moves into the previous timer and is killed, so it will naturally get stuck there.
So the biggest problem is that the entire program only has one timer. So how to solve this problem?
Solution:
In fact, it is very simple. Add the timer as the attribute of an object, so each object has a timer. When the timer is turned off, it is the timer on the object, and the timer on the object is also the timer on the object.
Then they can operate without interference with each other.
Look at the modified Javascript code:
The code copy 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 an object's property
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 have no problems and can support the movement of multiple objects.