I've been reading JavaScript books lately, and some things seem to be understandable in books, but in real hands, there are some details you don't understand. So it seems that even a simple effect, it is not easy to write, even if it is simple to write, the code is not necessarily standard, maintainability and so on. Helpless, has been learning programming has been above his business, resulting in anything can not be written out. When you don't have enough skills to write good code, learning Daniel's code is always an efficient way. Below is a drag-and-drop effect, reference code, refactoring below, to understand learning.
First look at the effect:
Drag Div
Drag-and-drop status: not started
"Program description"
Drag principle : Actually is in the drag block listens the MouseDown event, when the mouse clicks, obtains the corresponding coordinate parameter through the event object. Then, when the mouse moves, it listens to the MouseMove event on the document, gets the clientx and clienty coordinates of the mouse, and then sets the left and top of the dragged block.
First, listen to the MouseDown event.
Then add the MouseMove and MouseUp events on start
Monitor MouseMove and MouseUp event Eventutil.addeventhandler (document, "MouseMove", THIS._FM); Eventutil.addeventhandler (document, "MouseUp", THIS._FS);
When the mouse moves, 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 : Limit the top and left properties for the Lockx and Locky properties by judging them.
Range Limit Lock: limits the left and top values of a dragged block to a certain extent by calculating the width height of the container and dragging the width and height difference values of the block to set the maximum left and top values.
Full Demo:
<! DOCTYPE html>
JavaScript drag and drop effect