1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>拖拽--吸附效果--文字效果</title>
6 <style>
7 #div1{
8 width: 100px;
9 height: 100px;
10 background: red;
11 position: absolute;
12 }
13 #div1:hover{
14 cursor: pointer;
15 }
16 </style>
17 </head>
18 <body>
19 文字内容<br />
20 文字内容<br />
21 文字内容
22 <div id="div1">文字内容文字内容文字内容文字内容</div>
23 <script>
24 var oDiv = document.getElementById('div1');
25
26
27 var disX = 0; //鼠标的横向距离
28 var disY = 0; //鼠标的纵向距离
29
30 oDiv.onmousedown = function(ev){
31 var oEvent = ev || event;
32 disX = oEvent.clientX - oDiv.offsetLeft;
33 disY = oEvent.clientY - oDiv.offsetTop;
34
35 function mouseMove(ev){
36 var oEvent = ev || event;
37 var l = oEvent.clientX - disX; //div1的横向距离
38 var t = oEvent.clientY - disY; ////div1的纵向距离
39
40 //根据最新的鼠标坐标来确定div的坐标
41 oDiv.style.left = l + 'px';
42 oDiv.style.top = t + 'px';
43 }
44
45
46 function mouseUp(ev){
47 this.onmousemove = null;
48 this.onmouseup = null;
49
50 if(oDiv.releaseCapture){
51 oDiv.releaseCapture();
52 }
53 }
54
55 if(oDiv.setCapture){
56 //IE
57 oDiv.onmousemove = mouseMove;
58
59 oDiv.onmouseup = mouseUp;
60
61 oDiv.setCapture(); //事件捕获,解决IE9以下兼容问题
62 }else{
63 //chrome、ff
64 document.onmousemove = mouseMove;
65
66 document.onmouseup = mouseUp;
67 }
68
69 //解决火狐拖拽的bug,取消默认事件
70 return false; //解决chrome、ff、IE9的兼容问题
71 }
72 </script>
73 </body>
74 </html>