This article mainly introduces information about how javascript achieves drag-and-drop effects. If you need it, you can refer to the example in this article to share with you a drag-and-drop effect. Refer to the Code to refactor the following, understanding and learning.
First, let's take a lookEffect:
Drag p
Drag and Drop status: not started
[Program description]
Drag principle: in fact, listening to the mousedown event on the drag block, When you click the mouse, get the corresponding coordinate parameters through the event object. Then, when the mouse moves, it listens to the mousemove event on the document, obtains the clientX and clientY coordinates of the mouse, and sets the left and top of the drag block.
First, listen to the mousedown event
The Code is as follows:
EventUtil. addEventHandler (this. Drag, "mousedown", BindAsEventListener (this, this. Start ));
Then add the mousemove and mouseup events on Start.
// Listen to the events EventUtil. addEventHandler (document, "mousemove", this. _ fM); EventUtil. addEventHandler (document, "mouseup", this. _ fS );
When the mouse moves, set the left and top attributes of the drag block:
if(!this.LockX)this.Drag.style.left = iLeft + "px"; if(!this.LockY)this.Drag.style.top = iTop + "px";
Horizontal and vertical locking: you can determine the top and left attributes by determining the LockX and lockY attributes.
Range Limit lock: You can set the maximum left value and top value by calculating the difference between the width and the height of the drag block, to restrict the left and top values of the drag block to a certain range.
Complete DEMO:
JavaScript drag-and-drop effect
Drag p
Drag and Drop status: not started