拖拽的基本原理

要点:

  1. 计算物体与鼠标的距离
  2. onmousedown 后在有onmousemove动作,是按着移动
  3. 给document这么文档加onmousemove,这样能保证移动过快,物体还保持相对鼠标的位置
  4. onmouseup后,解除document上事件
  5. 解除onmousedown的默认行为,return false
 1 window.onload = function(){
 2     var oDiv = document.getElementById('div1');
 3     
 4     var disX = 0; //鼠标和物体之间的距离
 5     var disY = 0;
 6     
 7     oDiv.onmousedown = function(ev){
 8         var oEvent = ev || event;
 9         var self = this;
10         disX = oEvent.clientX - self.offsetLeft;
11         disY = oEvent.clientY - self.offsetTop;
12         
13         document.onmousemove = function(ev){
14             var oEvent = ev || event;
15             var l = oEvent.clientX - disX;
16             var t = oEvent.clientY - disY;
17             
18             
19             if (l < 0) {
20                 l=0;
21             }
22             else if(l > document.documentElement.clientWidth-self.offsetWidth){
23                 l = document.documentElement.clientWidth-self.offsetWidth;
24             }
25             if(t < 0){
26                 t = 0;
27             }else if(t > document.documentElement.clientHeight-self.offsetHeight){
28                 t = document.documentElement.clientHeight-self.offsetHeight;
29             }
30             
31             self.style.left = l + 'px';
32             self.style.top = t + 'px';
33         }
34         document.onmouseup = function(){
35             document.onmousemove = null;
36             document.onmouseup = null;
37         }
38         
39         return false;
40     }
41 };
原文地址:https://www.cnblogs.com/niubenbit/p/2784516.html