One, JS drag implementation Instance code:
Second, JS drag-and-drop effect
Main principle:
1, when the mouse is pressed, the record mouse coordinates, uses is the onmousedown;
2, when the mouse moves, the calculation of the mouse movement of the coordinates of the difference, the use of onmousemove;
3, when the mouse is loosened, the purge event, uses is onmouseup;
Understanding of Knowledge:
1, the offsetleft of Div and style.left difference: http://www.jb51.net/article/93142.htm
The effect chart is as follows:
Suddenly found there is no effect of the picture are the same haha, do not say nonsense, on the code:
HTML code:
JS Code:
Window.onload function () {var disx = Disy = 0; The mouse distance from the left and the distance div var div1 = document.getElementById ("Div1"); Get Div1 object//Div1 when mouse presses Div1.onmousedown = function (e) {var evnt = e | | event; Get mouse Event Disx = Evnt.clientx-div1.offsetleft; Mouse horizontal axis-Div1 left disy = evnt.clienty-div1.offsettop;
Mouse ordinate-DIV1 top//mouse Move Document.onmousemove = function (e) {var evnt = e | | event;
var x = Evnt.clientx-disx;
var y = Evnt.clienty-disy;
var window_width = document.documentelement.clientwidth-div1.offsetwidth;
var window_height = document.documentelement.clientheight-div1.offsetheight; x = (x < 0)? 0:x; x = (x > Window_width) when Div1 to the left of the window? window_width:x; y = (Y < 0) when Div1 to the far right of the window? 0:y; y = (y > Window_height) when Div1 to the top of the window? Window_height:y;
When Div1 to the bottom of the window Div1.style.left = x + "px";
Div1.style.top = y + "px";
}; Mouse lift when document.onmouseup = Function () {document.onmousemove =null;
Document.onmouup = null;
};
return false;
};
};
Of course, although this support most browsers, however, I think Div follow the mouse speed a bit lag, if there is a good solution please contact me Oh, thank you!
The above is a JS implementation of drag-and-drop instance code, there is a need for small partners can refer to, thank you for your support of this site!