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