Main principle:
1, when the mouse is pressed, record the mouse coordinates, use is onmousedown;
2, when the mouse movement, calculate the mouse movement coordinates difference, uses is onmousemove;
3, when the mouse release, clear the event, the use is onmouseup;
Knowledge of:
1, the offsetleft of Div and style.left difference:
http://longxu1314.blog.163.com/blog/static/2112990412013101814844444/
As follows:
Suddenly found that there are not all the same haha, do not say nonsense, on the code:
HTML code:
<! DOCTYPE html>Window.onload function () { var disx = disy = 0 ; // Mouse distance div left and upper distance var div1 = document.getelementbyid ("Div1"); // get Div1 object // Mouse Press Div1 div1.onmousedown = function (e) { var evnt = e | | event; // Get mouse Event disx = evnt.clientx - div1.offsetLeft; // Mouse Axis - div1 left disy = evnt.clienty - div1.offsettop; // Mouse Ordinate - div1 top // Mouse Movement 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; // when Div1 to the left of the window x = ( x > window_width ) ? window_width : x; // when Div1 to the right of the window y = ( y < 0 ) ? 0 : y; // when Div1 to the top of the window y = ( y > window_height ) ? window_height : y; // when Div1 to the bottom of the window div1.style.left = x + "px"; div1.style.top = y + "px"; }; // when the mouse lifts up document.onmouseup = function () { document.onmousemove =null; document.onmouup = null; }; return false; };};
Of course, although this support most browsers, but I think div follow the mouse speed a little lag, if there is a good solution please contact me Oh, thank you!
JS Drag effect