拷贝继承实现拖拽

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>继承的拖拽</title>
		<!--
			
			div1:表示最普通的拖拽,用它来充当父类,
			div2 :也是拖拽,用它来充当子类,但是它的拖拽有一定的限制范围,不能超出可视区域
			然后我们就通过拷贝继承来实现拖拽,并实现他们不一样的地方
		-->
		<style>
			#div1{width: 100px;height: 100px;background: red;position: absolute;cursor: pointer;}
			#div2{width: 100px;height: 100px;background: yellow;position: absolute;left: 100px;cursor: pointer;}
		</style>
	</head>
	<body>
		<div id = 'div1'></div>
		<div id = 'div2'></div>
		<script>
			window.onload = function(){
				var d1 = new Drag('div1');
				d1.init();
				var d2 = new childDrag('div2');
				d2.init();
			};
			
			function Drag(id){    // 父类
				this.obj = document.getElementById(id);
				this.disX = 0;
				this.disY = 0;
			}
			
			Drag.prototype.init = function(){
				var This = this;
				this.obj.onmousedown = function(ev){
					var ev = ev || window.event;
					This.fnDown(ev);
					
					document.onmousemove = function(ev){
						var ev = ev || window.event;
						This.fnMove(ev);
					};
					
					document.on,onmouseup = function(){
						This.fnUp();
					};
					
					// 阻止默认事件
					return false;  
				};
			};
			
			Drag.prototype.fnDown = function(ev){
				this.disX = ev.clientX - this.obj.offsetLeft;
				this.disY = ev.clientY - this.obj.offsetTop;
			};
			
			Drag.prototype.fnMove =function(ev){
				this.obj.style.left = ev.clientX - this.disX + 'px';
				this.obj.style.top = ev.clientY - this.disY + 'px';
			};
			
			Drag.prototype.fnUp = function(){
				document.onmousemove = null;
				document.onmouseup = null;
			};
			 
			function childDrag(id){    //子类
				// 继承父类属性
				Drag.call(this,id);  
			}
			
			// 实现继承父类方法
			extend(childDrag.prototype,Drag.prototype);
			
			//封装方法 通过for in 实现拷贝继承 父类方法
			function extend(obj1,obj2){
				for(var attr in obj2){
					obj1[attr] = obj2[attr];
				}
			}
			
			// 重写子类的fnMove方法 限制子类拖拽范围在可视区域
			childDrag.prototype.fnMove =function(ev){
				var L = ev.clientX - this.disX;
				var T = ev.clientY - this.disY;
				if(L < 0){
					L = 0;
				}else if(L > document.documentElement.clientWidth - this.obj.offsetWidth){
					L = document.documentElement.clientWidth - this.obj.offsetWidth;
				}
				
				if(T < 0){
					T = 0;
				}else if(T > document.documentElement.clientHeight - this.obj.offsetHeight){
					T = document.documentElement.clientHeight - this.obj.offsetHeight;
				}
				this.obj.style.left = L + 'px';
				this.obj.style.top = T + 'px';
			};
		</script>
	</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值