<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#wrap{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
cursor: pointer;
z-index: 2;
}
#obstacle{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
left: 300px;
top: 200px;
z-index: 1;
}
</style>
</head>
<body>
<div id="wrap"></div>
<!-- 障碍物 -->
<div id="obstacle"></div>
</body>
<script type="text/javascript">
var wrap = document.querySelector("#wrap");
var obstacle = document.querySelector("#obstacle");
wrap.onmousedown = function(e){
var e = e || window.event;
//鼠标的坐标
var oX = e.clientX;
var oY = e.clientY;
// 计算差值
var differL = oX - wrap.offsetLeft;
var differT = oY - wrap.offsetTop;
document.onmousemove = function(e){
var e = e || window.event;
// 改变wrap的位置
wrap.style.left = e.clientX - differL + "px";
wrap.style.top = e.clientY - differT + "px";
// 判断
var wrapLeft = wrap.offsetLeft;
var wrapTop = wrap.offsetTop;
var wrapRight = wrapLeft + wrap.offsetWidth;
var wrapBottom = wrapTop + wrap.offsetHeight;
var obstacleLeft = obstacle.offsetLeft;
var obstacleTop = obstacle.offsetTop;
var obstacleRight = obstacleLeft + obstacle.offsetWidth;
var obstacleBottom = obstacleTop + obstacle.offsetHeight;
if(wrapLeft <= obstacleRight && wrapTop <= obstacleBottom && wrapRight >= obstacleLeft && wrapBottom >= obstacleTop){
wrap.style.backgroundColor = "yellow";
}else{
wrap.style.backgroundColor = "red";
}
}
}
wrap.onmouseup = function(){
document.onmousemove = null;
}
</script>
</html>