完美拖拽

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <style>
 7             #div1{width: 200px;height:200px;background-color:red;position: absolute;}
 8         </style>
 9         <script>
10             window.onload=function(){
11                 var oDiv=document.getElementById('div1');
12                 var disX=0;
13                 var disY=0;
14 
15                 oDiv.onmousedown=function(ev){
16                     var oEvent=ev||event;
17 
18                     disX=oEvent.clientX-oDiv.offsetLeft;
19                     dixY=oEvent.clientY-oDiv.offsetTop;
20 
21                     if(oDiv.setCapture){
22                         document.onmousemove=mouseMove;
23                         document.onmouseup=mouseUp;
24                         oDiv.setCapture();
25                     }
26                     else{
27                         document.onmousemove=mouseMove;
28                         document.onmouseup=mouseUp;
29                     }
30 
31                     function mouseMove(ev){
32                         var oEvent=ev||event;
33                         var l=oEvent.clientX-disX;
34                         var t=oEvent.clientY-disY;
35 
36                         oDiv.style.left=l+'px';
37                         oDiv.style.top=t+'px';
38                     }
39                     function mouseUp(){
40                         this.onmousemove=null;
41                         this.onmouseup=null;
42 
43                         if(oDiv.releaseCapture){
44                             oDiv.releaseCapture();
45                         }
46                     }
47 
48                     return false;
49                 }
50             }
51         </script>
52     </head>
53     <body>
54         fawegagaerhbartharehaha
55         <p>awetgaegarehaerheraf</p>
56         <p>awetgaegarehaerheraf</p>
57         <div id="div1">
58             fawetawgagaer
59             agaregarehgaer
60         </div>
61         <p>awetgaegarehaerheraf</p>
62     </body>
63 </html>
完美拖拽
原文地址:https://www.cnblogs.com/shangec/p/12801336.html