js implements drag and drop and collision detection

This article mainly introduces the implementation of dragging and collision detection in js in detail. The sample code in the article is very detailed and has certain reference value. Interested friends can refer to it.

The example in this article shares the specific code of js for dragging and collision detection for your reference. The specific content is as follows

js实现拖拽与碰撞检测

drag and drop

Principle analysis

For dragging a div box, first we need to move the mouse to the box, then hold down the left mouse button, move the mouse to the target position, and release the mouse. For the analysis of this process,

Obviously three mouse events are required:

  • Hold down the mouse: onmousedown
  • Move the mouse: onmousemove
  • Release the mouse: onmouseup

Implementation steps

1. **When the mouse is pressed: **We obtain the distance between the current position of the mouse and the left border and the upper border of the page, and subtract the value of the box from the left border and the upper border of the page respectively, so that we

The value of the mouse distance from the left border and the upper border of the box is obtained;

2. **When the mouse moves: **We re-obtain the value of the mouse distance from the left border and the upper border of the page at this time, and then use them to subtract the mouse distance from the left border and the upper border of the box obtained in step 1.

value, and reassign the obtained value to the box, so that the box can remain relatively still with the mouse and move on the page;

3. **When the mouse is released: **Clear the mouse movement event.

Implementation code

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

The post js Implementing Drag and Collision Detection first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9884
This site is for inclusion only, and the copyright belongs to the original author.