比较有意思的原生态js拖拽写法----摘自javascript高级程序设计3
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; width:100px; height:100px;left:0px"></div> 3 <div class="draggable" style="position:absolute; background-color:Red; width:100px; height:100px;left:200px"></div> 4 <div class="draggable" style="position:absolute; background-color:Red; width:100px; height:100px;left:500px"></div> 5 <div class="draggable" style="position:absolute; background-color:Red; width:100px; height:100px;left:800px"></div> 6 </body>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。