一、效果展示
二、完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#collide {
height: 600px;
width: 100%;
position: relative;
}
#move {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
#box {
position: absolute;
width: 200px;
height: 200px;
background-color: gray;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
</head>
<body>
<div id="collide">
<div id="box"></div>
<div id="move"></div>
</div>
</body>
<script type="text/javascript">
var move = document.getElementById("move");
var box = document.getElementById("box");
move.onmousedown = function(e) {
var t = e.clientY - move.offsetTop;
var l = e.clientX - move.offsetLeft;
document.onmousemove = function(e) {
var top = e.clientY - t;
var left = e.clientX - l;
move.style.top = top + "px";
move.style.left = left + "px";
if(top + move.offsetHeight >= box.offsetTop
&& top <= box.offsetTop + box.offsetHeight) {
if(left + move.offsetWidth + 50 >= box.offsetLeft
&& left + move.offsetWidth<= box.offsetLeft + box.offsetWidth) {
left = box.offsetLeft - move.offsetWidth;
move.style.left = left + "px";
}
else if(left - 50 <= box.offsetLeft + box.offsetWidth
&& left > box.offsetLeft + box.offsetWidth - move.offsetWidth) {
left = box.offsetLeft + box.offsetWidth;
move.style.left = left + "px";
}
}
if(
move.offsetLeft + move.offsetWidth >= box.offsetLeft
&& move.offsetLeft <= box.offsetLeft + box.offsetWidth
&& move.offsetTop + move.offsetHeight >= box.offsetTop
&& move.offsetTop <= box.offsetTop + box.offsetHeight
) {
box.style.backgroundColor = "yellow";
} else {
box.style.backgroundColor = "gray";
}
}
}
move.onmouseup = document.onmouseup = function() {
document.onmousemove = null;
}
</script>
</html>