HTML section
<div id="div1"></div> <div id="div2" ></div>
CSS Section
<style> #div1 {width:100px;height:100px;background-color:red;position:absolute;} #div2 {width:100px;height:100px;background-color:blue;position:absolute;left:100px;} </style>
Common JS notation
//General Wordingfunction Drag (ID) {varobj =document.getElementById (ID); varDISX =0; varDisy =0; Obj.onmousedown=function (EV) {varEV = EV | | Window.Event; DISX= Ev.clientx-Obj.offsetleft; Disy= Ev.clienty-Obj.offsettop; Document.onmousemove=function (EV) {varEV = EV | | Window.Event; Obj.style.left= Ev.clientx-disx +"px"; Obj.style.top= Ev.clienty-disy +"px"; } document.onmouseup=function () {Document.onmouseup= Document.onmousemove =NULL; } }} window.onload=function () {Drag ("Div1"); Drag ("Div2");}
Object-oriented notation:
function Drag (ID) { This. obj =document.getElementById (ID); This. DISX =0; This. Disy =0; } Drag.prototype.init=function () {varthat = This; This. Obj.onmousedown =function (EV) {varEV = EV | | Window.Event; That.fndown (EV); Document.onmousemove=function (EV) {varEV = EV | | Window.Event; That.fnmove (EV); } document.onmouseup=function () {Document.onmousemove=NULL; Document.onmouseup=NULL; } } return false; } Drag.prototype.fnDown=function (EV) { This. DISX = Ev.clientx- This. Obj.offsetleft; This. Disy = Ev.clienty- This. Obj.offsettop; }; Drag.prototype.fnMove=function (EV) { This. Obj.style.left = Ev.clientx- This. Disx +'px'; This. obj.style.top = Ev.clienty- This. Disy +'px'; };
Inherits the child component of the parent class function Childdrag (ID) {Drag.call ( This, id); }
function Extend (obj1,obj2) { for(varattrinchobj2) {Obj1[attr]=Obj2[attr]; }} extend (Childdrag.prototype,drag.prototype);
Redefine the Fnmove function ChildDrag.prototype.fnMove=function (EV) {varL = Ev.clientx- This. Disx; varT = Ev.clienty- This. Disy; if(l<0) {L=0; }Else if(L>document.documentelement.clientwidth- This. Obj.offsetwidth) {L= Document.documentElement.clientWidth- This. Obj.offsetwidth; } if(t<0) {T=0; }Else if(T>document.documentelement.clientheight- This. Obj.offsetheight) {T= Document.documentElement.clientHeight- This. Obj.offsetheight; } This. Obj.style.left = L +'px'; This. Obj.style.top = T +'px'; }; Window.onload=function () {varobj =NewDrag ("Div1"); Obj.init (); varObj2 =NewChilddrag ("Div2"); Obj2.init (); }
Drag-and-drop functionality and extension of components