JS事件对象(练习与复习)--碰撞检测(函数回调)

1.碰撞检测:
CSS+Body部分:

<style type="text/css">
	#first
	{
		width:100px;
		height:100px;
		background:pink;
		position:absolute;
	}
	#second{
		width:100px;
		height:100px;
		background:blue;
		position:absolute;
		top:100px;
		left:200px;
		color:#ccc;
	}
	</style>
</head>
<div id="first"></div>
<div id="second"></div>	
</body>

JS部分:

<script type="text/javascript" src="2.collision.js"></script>
<script type="text/javascript">
	var first=document.querySelector('#first');
	var second=document.querySelector('#second');
//碰撞检测----通用性,代码如何通用,函数回调一般用于封装函数
	move(first,second,
		//碰撞 
		function(){second.style.background='red';
	               second.innerHTML='已撞上';},
		//未碰撞
		function(){second.style.background='blue';
		           second.innerHTML='未撞上';
	                });	
</script>

2.上述引用的2.collision.js为:

//碰撞检测
	function collision(moveObj_1,endObj_1,rightCall,falseCall){
		//左右
		var minX=endObj_1.offsetLeft-moveObj_1.offsetWidth;
		var maxX=endObj_1.offsetLeft+endObj_1.offsetWidth;
		//上下
		var minY=endObj_1.offsetTop-moveObj_1.offsetHeight;
		var maxY=endObj_1.offsetTop+endObj_1.offsetHeight;
        //碰撞检测
        if(moveObj_1.offsetLeft>=minX&&moveObj_1.offsetLeft<=maxX&&
        	moveObj_1.offsetTop>=minY&&moveObj_1.offsetTop<=maxY)
        {
        	
        		rightCall();
        }
          else
          {
          	
          		falseCall();
          	
          }



	}

	function move(moveObj,endObj,rightCall,falseCall)
	{
		moveObj.onmousedown=function(e)
	 {
		
		var ev=e||window.event;
		var current_X=ev.offsetX;
		var current_Y=ev.offsetY;
		
		document.onmousemove=function(e)
		{
           var ev=e||window.event;
           var off_x=ev.clientX;
           var off_y=ev.clientY;
         moveObj.style.left=off_x-current_X+"px";
           moveObj.style.top=off_y-current_Y+"px";
           collision(moveObj,endObj,rightCall,falseCall);
          
		}
		document.onmouseup=function()
		{
			document.onmousemove=null;
		}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值