To achieve arbitrary div drag, we may wish to analyze the entire process.
When you click a div, an event is triggered, so that the position attribute (left, top) of the div changes with the mouse position. When the mouse is released, the position attribute of the div is the position when the mouse is released.
It is easy to trigger an event when you click the mouse. You only need to add onmouseclick to the div tag, now we need to solve the problem of changing the div position with the mouse position.
Although this may be a very simple reasoning process, let's clarify it. The left and top of the div are the coordinates of the upper left corner of the div. When we move the cursor to the div and click it, the coordinates of the mouse and the div are undoubtedly inconsistent, at this time, if we simply make the div coordinate equal to the mouse coordinate, then the effect looks not so perfect, so we need to first get the difference between the mouse coordinate and the div coordinate, then, when you move the mouse, subtract the difference from the mouse coordinate to get the div coordinate (if you do not quite understand it, first tutorial the basic knowledge of the web page ).
The next thing is simple. When the mouse moves, we constantly get the coordinates of the div and change it. When the mouse is released, this event is removed.
The js function is as follows:
Function beginDrag (elementToDrag, event)
{
Var deltaX = event. clientX-parseInt (elementToDrag. style. left );
Var deltaY = event. clientY-parseInt (elementToDrag. style. top );
If (document. addEventListener)
{
Document. addEventListener ("mousemove", moveHandler, true );
Document. addEventListener ("mouseup", upHandler, true );
// Document. addEventListener ("mouseout", upHandler, true );
}
Else if (document. attachEvent)
{
Document. attachEvent ("onmousemove", moveHandler );
Document. attachEvent ("onmouseup", upHandler );
// Document. attachEvent ("onmouseout", upHandler );
}
If (event. stopPropagation) event. stopPropagation ();
Else event. cancelBubble = true;
If (event. preventDefault) event. preventDefault ();
Else event. returnValue = false;
Function moveHandler (e)
{
If (! E) e = window. event; // if it is an event object of IE, use window. event
// Global attribute. Otherwise, the DOM second-level standard Event object is used.
ElementToDrag. style. left = (e. clientX-deltaX) + "px ";
ElementToDrag. style. top = (e. clientY-deltaY) + "px ";
If (e. stopPropagation) e. stopPropagation ();
Else e. cancelBubble = true;
}
Function upHandler (e)
{
If (document. removeEventListener)
{
Document. removeEventListener ("mouseup", upHandler, true );
Document. removeEventListener ("mousemove", moveHandler, true );}
Else
{
Document. detachEvent ("onmouseup", upHandler );
Document. detachEvent ("onmousemove", moveHandler );}
}
If (! E) e = window. event;
If (e. stopPropagation) e. stopPropagation ();
Else e. cancelBubble = true;
}