Objective
In the afternoon to write a can drag-and-drop example, stay in mind has been three events mousedown,mouseup,mousemove, but never hands-on practice, today think of their own practice and learn Zhang Xin Xu's demo implementation. Learn Zhang Xin Xu code at the same time and understand a few knowledge points.
1, obj.currentstyle[attr] and getComputedStyle (obj,false) [attr]. Gets the non-inline style of the DOM. I Baidu the next currentstyle see some said Chrome and FF is not supported, in order to be compatible, so use these two methods.
2, onselectstart. IE and chrome are applied to prevent content from being selected by default to True.
Principle of drag and pull
1, Draggable Div is mainly to determine the MouseDown event occurs when the DOM bearer object, and MouseMove coordinate calculation.
2. Next, the DOM hosts the object when the drag is completed. Most will choose document, do not know I understand it right?
Js
/** Drag div Key event: MouseDown, Mousemove,mouseup**/var params={top:0,left:0,currentx:0,currenty:0,flag:false};/** Obj.currentstyle[attr]getcomputedstyle (Obj,false) [attr] get DOM non-inline style **/var getcss=function (o,key) {return O.currentstyle? O.currentstyle[key]: Document.defaultView.getComputedStyle (O,false) [key];} var startdrag=function (Bar,target,callback) {if (Getcss (target, ' left ')! = ' auto ') {params.left=getcss (target, ' left ') ;} if (Getcss (target, ' top ') = ' auto ') {params.top=getcss (target, ' top ');} Bar.onmousedown=function (event) {params.flag=true;if (!event) {event=window.even;bar.onselectstart=function () {// IE and chrome are applied to prevent content from being selected by default Truereturn false;}} var E=event;params.currentx=e.clientx;params.currenty=e.clienty;} Document.onmouseup=function () {params.flag=false;if (Getcss (Target, "left")! = ' auto ') {params.left=getcss (target, ' Left ');} if (Getcss (target, ' top ') = ' auto ') {params.top=getcss (target, ' top ');}} Document.onmousemove=function (event) {var e=event?event:window.event;if (params.flag) {var nowx=e.clientx,nowy=e.clIenty;var Disx=nowx-params.currentx, Disy=nowy-params.currenty;target.style.left=parseint (params.left) +disX+ ' px ' ; Target.style.top=parseint (params.top) +disy+ ' px ';} if (callback== ' function ') {callback (parseint (Params.left) +disx,parseint (params.top) +disy);}}}
: Http://yunpan.cn/cwTJmDQWtAgLs access Password 7d22
JS to implement a draggable div