This article mainly introduces how to move any element to a specified position with js. It has certain reference value. Now I share it with you. Friends in need can refer to it.
Idea: Move an element to Specifying the location ====== requires passing in 2 parameters. One is the element to be moved, and the other is the specified position target.
Get the current position of the element, set a distance step for each movement, set a timer, and reach the target position through multiple circular movements. Determine whether a loop needs to be executed based on the distance between the current position and the target position
Take this article as an example. There are several pitfalls here:
1. To move an element, it needs to be separated from the document flow. That is, absolute positioning needs to be used in the css style
2. Every time a click is triggered, a timer is generated. When the button is clicked continuously, the element moves faster
===》Solution: Set only one timer, and clean the timer before executing the timer to prevent the last operation from leaving any impact.
Only setting a timer can be based on the properties of the object. There is only one property clicked on the object. That is, element.timer1=setInterval();
3. To get the current position of the element, you need to use offsetLeft / offsetTop / offsetWidth / offsetHeight. The result is of type number, without px
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
About the implementation of JS effect function
How to randomly sort js arrays
The above is the detailed content of js moves any element to a specified position. For more information, please follow other related articles on the PHP Chinese website!