<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{width:150px;height:150px;position:absolute;background-color:red ;z-index:1;border-radius:50%;}
#div2{width:200px;height:200px;position:absolute;background-color:blue ;left:500px;top:400px;border-radius:50%;}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script>
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
div1.onmousedown = function(ev){
var disX = ev.clientX-div1.offsetLeft; //鼠标距离左边框的距离
var disY = ev.clientY-div1.offsetTop; //鼠标距离上边框的距离
document.onmousemove = function(ev){
var left = ev.clientX-disX;
var top = ev.clientY-disY;
div1.style.left = left+"px";
div1.style.top = top+"px";
if(test_collision(div1,div2)){div2.style.background = "blue";}
else{div2.style.background = "yellow";}
//console.log(test_collision(div1,div2));
document.onmouseup = function(){
document.onmousedown = null;
document.onmousemove = null;
}
}
}
function test_collision(obj1,obj2){ //obj1是拖拽元素,obj2是被碰撞元素
var obj1_width = obj1.offsetWidth; //div1的宽度
var obj1_height = obj1.offsetHeight; //高度
var obj1_left = obj1.offsetLeft;
var obj1_top = obj1.offsetTop;
var obj2_width = obj2.offsetWidth; //div2的宽度
var obj2_height = obj2.offsetHeight; //高
var obj2_left = obj2.offsetLeft; //左边距
var obj2_top = obj2.offsetTop; //上边距
if(obj1_left+obj1_width<obj2_left||obj1_left>obj2_width+obj2_left||
obj1_top+obj1_height<obj2_top||obj1_top>obj2_top+obj2_height) //没有撞到,安全,返回true
{return true;}
else {return false;}
/*
if(obj1_left+obj1_width>obj2_left&&obj2_left+obj2_width>obj1_left&& //撞到了,不安全,返回false
obj1_top+obj1_height>obj2_top&&obj2_top+obj2_height>obj1_top)
{return false;}
else{return true;}
*/
}
</script>
</body>
</html>