The example of this article for everyone to share is a drag-and-drop effect, reference code, refactoring the following to understand learning.
First look at the effect:
Drag Div
Drag-and-drop status: Not Started
"Program description"
Drag principle: In fact, is in the drag block listening to the MouseDown event, the mouse clicks, through the event object to obtain the corresponding coordinate parameters. Then, when the mouse moves, listen for the MouseMove event on the document, get the mouse clientx and clienty coordinates, and then set the left and top of the drag block.
First, listen for MouseDown events.
Copy Code code as follows:
Eventutil.addeventhandler (this. Drag, "MouseDown", Bindaseventlistener (this, this. Start));
Then add the MouseMove and MouseUp events on the start
Monitor MouseMove and MouseUp events
Eventutil.addeventhandler (document, "MouseMove", this._fm);
Eventutil.addeventhandler (document, "MouseUp", THIS._FS);
When you move the mouse, set the left and top properties 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 restrict the top and left properties for the Lockx and Locky properties by judging them.
Scope Limit Locking: Sets the maximum left and top values by calculating the width of the container and the width-height difference of the drag block, to limit the left value of the drag block and the highest value to a certain range.
Full Demo:
The above is JavaScript implementation of drag-and-drop effect of the code, I hope to help you learn.