1. There are three events to be dragged, onmousedown, onmousemove, and onmouseup
2. In the onmousemove event, the position change of the dragged element is processed. In fact, to put it bluntly, the distance the element needs to move is the distance between the two movements of the mouse. distance between.
3. It also includes setCapture and releaseCapture. The purpose is to ensure that the moved element always has focus.
This is roughly the previous understanding. You can refer to JS drag technology---about the implementation of setCapture. Later, with the improvement of work requirements, all the work must be cross-browser, so I re-conceived and implemented it with reference to some open source code.
Now the general idea can be analyzed into the following steps, I will show you one by one.
1. Are we moving for the sake of dragging? Of course not, like Google Maps, its purpose is to calculate the current spatial coordinates to load geographical information after each move. So I have designed several common events here. The following is the event list
onDragStart: When an element is dragged, if you register this event, it will receive two parameters x and y when triggered, which are the coordinates of the moved element when it is dragged.
onDrag: Element dragging During the process, if you register this event, you will receive two parameters nx and ny when it is triggered. The offset of the coordinates during the dragging process
onDragEnd: When the element ends, if you register this event, you will receive two parameters when it is triggered. The parameters x and y are respectively the current coordinates of the moved element
2. Who should the onmousedown event be bound to? In the past, I bound it to the dragged element. Later, I found that it was very inflexible. Now it is designed to be bindable. Given any unrelated elements, drag the elements at the same time.
3. How to ensure that the element always has focus during the moving process? Because it is cross-browser, we no longer use methods such as setCapture. Here is another way of thinking, why is there no focus during the element moving process? The main reason is that we register the onmousemove event to the dragged element, and this It is not necessary, so when the element triggers the onmousedown event, I register the onmousemove and onmouseup events directly to the document, so that wherever the mouse moves, there will be focus.
After saying so much, let’s look directly at the code structure!