This time I will bring you the implementation method of JS multi-object movement. What are the precautions for the implementation of JS multi-object movement. The following is a practical case, let's take a look.
The basic steps
1. Obtain the elements to be moved by multiple objects through getElementsByTagName
2. Then traverse the elements in a for loop and add events
3. Define the startMove function, which requires two parameters. Currently "doing movement" " element, and the target value target
Attention: In multi-object motion, everything cannot be shared;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
question:
When the moving in and out speed is relatively fast, some li will not be able to return to its original state and will get stuck in the middle; This is because all li's share a timer;
When the mouse moves into the first li, startMove is called to start a timer; when the mouse removes the li, a timer also needs to be started to return the li to its original position. When the li reaches halfway, we move into the second li. First The timer will be cleared, and at this time the first li will be stuck halfway.
Solve this problem: Let each li have its own timer to control their changes. During the for loop, define its own timer for each li
1 |
|
Then, the timer used each time in starMove is the current li's own, so there will be no interference with each other.
The previous timer here has been changed to obj.timer
(the current object’s own timer); there is no problem here.
The complete code is as follows:
1 |
|
Add dot style:
1 2 3 4 5 6 7 8 |
|
Complete js code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Next, let’s look at an example: Multi-object movement - changing transparency
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to handle the failure of rendering page when vue route is refreshed in history mode
##vue. Detailed explanation of the steps to achieve seamless scrolling effect with js
The above is the detailed content of How to implement multi-object motion in JS. For more information, please follow other related articles on the PHP Chinese website!