基于继承的拖拽

 1     window.onload = function() {
 2         new Drag("div1");
 3         new LimitDrag("div2");
 4     };
 5 
 6     //父类
 7     function Drag(id) {
 8         var _this = this;
 9 
10         this.disX = 0;
11         this.disY = 0;
12         this.oDiv = document.getElementById(id);
13 
14         this.oDiv.onmousedown = function() {
15             _this.fnDown();
16         };
17     }
18 
19     Drag.prototype.fnDown = function(ev) {
20         var _this = this;
21 
22         var oEvent = ev || event;
23         this.disX = oEvent.clientX - this.oDiv.offsetLeft;
24         this.disY = oEvent.clientY - this.oDiv.offsetTop;
25 
26         document.onmousemove = function() {
27             _this.fnMove();
28         };
29 
30         document.onmouseup = function() {
31             _this.fnUp();
32         };
33 
34         //兼容FF
35         return false;
36     };
37 
38     Drag.prototype.fnMove = function(ev) {
39         var oEvent = ev || event;
40 
41         var l = oEvent.clientX - this.disX;
42         var t = oEvent.clientY - this.disY;
43 
44         this.oDiv.style.left = l + "px";
45         this.oDiv.style.top = t + "px";
46     };
47 
48     Drag.prototype.fnUp = function(ev) {
49         document.onmousemove = null;
50         document.onmouseup = null;
51     };
52 
53     //子类
54     function LimitDrag(id) {
55         Drag.call(this, id);
56     }
57 
58     //继承父类的属性和方法
59     for (var i in Drag.prototype) {
60         LimitDrag.prototype[i] = Drag.prototype[i];
61     }
62 
63     //重写父类的方法
64     LimitDrag.prototype.fnMove = function(ev) {
65         var oEvent = ev || event;
66 
67         var l = oEvent.clientX - this.disX;
68         var t = oEvent.clientY - this.disY;
69 
70         if (l < 0) {
71             l = 0;
72         } else if (l > document.documentElement.clientWidth - this.oDiv.offsetWidth) {
73             l = document.documentElement.clientWidth - this.oDiv.offsetWidth;
74         }
75 
76         if (t < 0) {
77             t = 0;
78         } else if (t > document.documentElement.clientHeight - this.oDiv.offsetHeight) {
79             t = document.documentElement.clientHeight - this.oDiv.offsetHeight;
80         }
81 
82         this.oDiv.style.left = l + "px";
83         this.oDiv.style.top = t + "px";
84     };

 

posted @ 2015-12-24 20:13  叫我霍啊啊啊  阅读(95)  评论(0编辑  收藏  举报