![]()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
z-index: 1;
}
#box2 {
width: 300px;
height: 200px;
background: green;
position: absolute;
left: 500px;
top: 300px;
}
</style>
</head>
<body>
<div id="box"></div>
<div id="box2"></div>
<script>
var box = document.getElementById('box');
var box2 = document.getElementById('box2');
// 一打开就求box2的四边距离
var L2 = box2.offsetLeft;
var T2 = box2.offsetTop;
var R2 = box2.clientWidth + L2;
var B2 = box2.clientHeight + T2;
console.log(L2, T2, R2, B2);
box.onmousedown = function (ev) {
// 设置全局捕获,兼容IE8及以下
if (box.setCapture) {
box.setCapture();
}
var ev = ev || event;
// 可视区宽高
var clientW = document.documentElement.clientWidth;
var clientH = document.documentElement.clientHeight;
// 盒子宽高
var boxW = box.clientWidth;
var boxH = box.clientHeight;
// 鼠标到盒子的距离
var disX = ev.clientX - box.offsetLeft;
var disY = ev.clientY - box.offsetTop;
// 拖动
document.onmousemove = function (ev) {
var ev = ev || event;
var L = ev.clientX - disX; // 盒子到左边的距离
var T = ev.clientY - disY; // 盒子到顶部的距离
if (L < 0) {
L = 0;
} else if (L > clientW - boxW) {
L = clientW - boxW;
}
if (T < 0) {
t = 0;
} else if (T > clientH - boxH) {
T = clientH - boxH;
}
box.style.left = L + 'px';
box.style.top = T + 'px';
// 求拖动盒子的四边距离
var L1 = L;
var T1 = T;
var R1 = L1 + boxW;
var B1 = T1 + boxH;
// 判断box与box2是否碰撞
if (R1 < L2 || B1 < T2 || L1 > R2 || T1 > B2) { // 未碰撞,box2维持原色
box2.style.background = 'green';
} else { // 发生碰撞,box2变为黄色
box2.style.background = 'yellow';
}
}
// 抬起
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
// 释放全局捕获,兼容IE8及以下
if (box.releaseCapture) {
box.releaseCapture();
}
}
return false; // 阻止浏览器默认行为
}
</script>
</body>
</html>