拖拽三部曲:
1、鼠标按下:获取鼠标当前按下的位置,阻止浏览器默认行为,添加监听事件,清除浏览器默认选择的文本,处理IE在容器内的鼠标事件被容器捕获。
2、鼠标移动:获取鼠标位置,设置对象的位置,阻止浏览器默认行为。
3、鼠标抬起:移除事件监听。
View Code
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>一步一步理解拖拽Drag(二)</title>
5 <script type="text/javascript">
6 var base = {
7 getId: function (id) {
8 return document.getElementById(id);
9 },
10 addEvent: function (element, type, fn) {
11 if (element.addEventListener) {
12 element.addEventListener(type, fn, false);
13 }
14 else if (element.attachEvent) {
15 element.attachEvent("on" + type, fn);
16 }
17 else {
18 element["on" + type] = fn;
19 }
20 },
21 removeEvent: function (element, type, fn) {
22 if (element.removeEventListener) {
23 element.removeEventListener(type, fn, false);
24 }
25 else if (element.detachEvent) {
26 element.detachEvent("on" + type, fn);
27 }
28 else {
29 element["on" + type] = null;
30 }
31 },
32 unDefaultEvent: function (event) {
33 if (event && event.preventDefault) {
34 event.preventDefault();
35 }
36 else {
37 event.returnValue = false;
38 }
39 }
40 };
41
42
43 (function () {
44 function Drag(obj) {
45 this.obj = obj;
46 this.disX = this.disY = 0;
47 var _this = this;
48 base.addEvent(obj, "mousedown", function (event) {
49 _this.startDrag(event);
50 });
51 }
52
53 Drag.prototype = {
54
55 startDrag: function (event) {
56 base.unDefaultEvent(event);
57
58 var _this = this;
59
60 this.disX = event.clientX - this.obj.offsetLeft;
61 this.disY = event.clientY - this.obj.offsetTop;
62
63 this.mousemoveHandle = function (event) {
64 _this.move(event);
65 };
66
67 this.mouseupHandle = function () {
68 _this.stopDrag();
69 };
70
71 base.addEvent(document, "mousemove", this.mousemoveHandle);
72
73 base.addEvent(document, "mouseup", this.mouseupHandle);
74
75 if (document.selection && document.selection.empty) {
76 document.selection.empty();
77 }
78 else if (window.getSelection) {
79 window.getSelection().removeAllRanges();
80 }
81
82 if (this.obj.setCapture) {
83 this.obj.setCapture(true);
84 }
85
86 },
87 move: function (event) {
88 base.unDefaultEvent(event);
89 this.obj.style.left = event.clientX - this.disX + "px";
90 this.obj.style.top = event.clientY - this.disY + "px";
91
92 },
93 stopDrag: function () {
94 base.removeEvent(document, "mousemove", this.mousemoveHandle);
95 base.removeEvent(document, "mouseup", this.mouseupHandle);
96
97 if (this.obj.releaseCapture) {
98 this.obj.releaseCapture(true);
99 }
100 }
101 };
102
103 base.addEvent(window, "load", function (event) {
104 var odiv = base.getId("mdiv");
105 var d = new Drag(odiv);
106 });
107
108 })();
109 </script>
110 </head>
111 <body>
112 <div id="mdiv" style="width: 300px; height: 100px; position: absolute; border: 1px solid red;
113 cursor: move">
114 </div>
115 </body>
116 </html>