<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <Metaname= "viewport"content= "width=device-width, initial-scale=1.0"> <Metahttp-equiv= "x-ua-compatible"content= "ie=edge"> <title>Document</title> <style>#box{position:Absolute;width:200px;Height:200px;background:Red; } </style> <Script>window.onload=function(){ varDrag=NewDrag ("Box") Drag.init (); } //Constructor Drag functionDrag (id) { this. obj=document.getElementById (id); this. Disx=0; this. Disy=0; } Drag.prototype.init= function (){ varMe= this; this. Obj.onmousedown= function(e) {vare=e||event; Me.mousedown (e); //Block Default Events return false; }; }; Drag.prototype.mouseDown=function(e) {varMe= this; this. Disx=E.clientx- this. obj.offsetleft; this. Disy=E.clienty- this. obj.offsettop; Document.onmousemove=function(e) {vare=e||window.event; Me.mousemove (e); }; Document.onmouseup= function() {me.mouseup (); }} Drag.prototype.mouseMove= function(e) { this. Obj.style.left=(e.clientx- this. Disx)+ 'px'; this. Obj.style.top=(e.clienty- this. Disy)+ 'px'; }; Drag.prototype.mouseUp= function() {document.onmousemove= NULL; //If you do not uninstall this event, when the mouse is lifted, move the mouse, the div will still Move. Document.onmouseup= NULL; };
Using JavaScript to achieve drag-and-drop effects