拖拽-吸附

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

 

posted @ 2020-04-29 12:12  孝文  阅读(108)  评论(0编辑  收藏  举报