基于继承的拖拽

 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     };

 

转载于:https://www.cnblogs.com/huoteng/p/5049878.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值