1 var DragDrop = function () { 2 var dragging = null; 3 var diffX = 0; 4 var diffY = 0; 5 function handleEvent(event) { 6 event = EventUtil.getEvent(event); 7 var target = EventUtil.getTarget(event); 8 switch (event.type) { 9 case "mousedown": 10 if (target.className.indexOf("draggable") > -1) { 11 dragging = target; 12 diffX = event.clientX - target.offsetLeft; 13 diffY = event.clientY - target.offsetTop; 14 } 15 break; 16 case "mousemove": 17 if (dragging !== null) { 18 dragging.style.left = (event.clientX - diffX) + "px"; 19 dragging.style.top = (event.clientY - diffY) + "px"; 20 } 21 break; 22 case "mouseup": 23 dragging = null; 24 break; 25 } 26 } 27 return { 28 enable : function () { 29 EventUtil.addHandler(document, "mousedown", handleEvent); 30 EventUtil.addHandler(document, "mousemove", handleEvent); 31 EventUtil.addHandler(document, "mouseup", handleEvent); 32 }, 33 disable : function () { 34 EventUtil.addHandler(document, "mousedown", handleEvent); 35 EventUtil.addHandler(document, "mousemove", handleEvent); 36 EventUtil.addHandler(document, "mouseup", handleEvent); 37 } 38 } 39 } (); 40 window.onload = function () { 41 DragDrop.enable(); DragDrop.disable(); 42 }
1 <body> 2 <div class="draggable" style="position:absolute; background-color:Red; 100px; height:100px;left:0px"></div> 3 <div class="draggable" style="position:absolute; background-color:Red; 100px; height:100px;left:200px"></div> 4 <div class="draggable" style="position:absolute; background-color:Red; 100px; height:100px;left:500px"></div> 5 <div class="draggable" style="position:absolute; background-color:Red; 100px; height:100px;left:800px"></div> 6 </body>