Drag and drop is a very common function in front-end development and one of the basic skills. This article is drag without limiting the scope, which is the simplest drag. Press the object with the mouse, drag and drop, and then stop!
1, onmousedown event
2, onmousemove event
3. Onmouseup event
Because it is dragged when pressed, the onmousemove event is registered only after down. The up event is used to unbind the event and eliminate the event!
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Simple drag and drop</title> <style type="text/css"> * { margin: 0; padding: 0; } #div1 { width: 100px; height: 100px; background: orange; position: absolute; } </style> </head> <body style="height: 500000px;"> <div ></div> <script type="text/javascript"> function getStyle(obj, attr) { if () { return [attr]; } else { return getComputedStyle(obj, null)[attr]; } } var oDiv = ('div1'); = function(ev) { var oEvent = ev || event; // var disX = - ; // var disY = - ; var disX = - parseInt(getStyle(oDiv, 'left')); var disY = - parseInt(getStyle(oDiv, 'top')); = function(ev) { var oEvent = ev || event; = - disX + 'px'; = - disY + 'px'; }; = function() { = null; = null; }; return false; }; </script> </body> </html>
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.