<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>检查两个div是否有碰撞</title>
<style>
#box1 {
width: 100px;
height: 100px;
position: absolute;
left: 200px;
top: 350px;
background: lightcoral;
}
#box2 {
width: 100px;
height: 100px;
position: absolute;
left: 0px;
top: 0px;
background: lightgreen;
}
</style>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
<script>
// 1. 获取两个div对象
var box1 = document.querySelector('#box1');
var box2 = document.querySelector('#box2');
// 2. 给box2绑定鼠标点击事件
box2.onmousedown = function(e) {
// 2.1 获取鼠标点击到box2的那个位置
e = e || event;
var posX = e.clientX - this.offsetLeft; // this指的是box2,在那个对象上按下了鼠标,那个对象就是this
var posY = e.clientY - this.offsetTop;
// 3. 给document绑定移动事件
document.onmousemove = function(e) {
// 3.1计算box2移动到的位置
e = e || event;
var left = e.clientX - posX;
var top = e.clientY - posY;
// 3.2给box2重新设定top和left
box2.style.left = left + 'px';
box2.style.top = top + 'px';
// 3.3判断box2是否碰撞box1
// 3.3.1 分别计算box1和box2的 的距离
var b1Left = box1.offsetLeft;
var b1Right = b1Left + box1.offsetWidth;
var b1Top = box1.offsetTop;
var b1Bottom = b1Top + box1.offsetHeight;
var b2Left = box2.offsetLeft;
var b2Right = b2Left + box2.offsetWidth;
var b2Top = box2.offsetTop;
var b2Bottom = b2Top + box2.offsetHeight;
// 3.3.2比较上一步计算出来的值
if (b2Right < b1Left || b1Right < b2Left || b2Bottom < b1Top || b1Bottom < b2Top) {
// 3.3.3如果没有碰撞box1的背景色设置为lightcoral
box1.style.background = 'lightcoral';
} else {
// 3.3.4如果碰撞成立把box1的背景色设置为灰色
box1.style.background = 'lightgray';
}
};
// 4. 给document绑定鼠标释放事件
document.onmouseup = function() {
// 4.1 给移动事件设置为null
document.onmousemove = null;
// 4.2给释放事件设置为null
document.onmouseup = null;
}
}
</script>
</html>
js实现检查两个div是否有碰撞
最新推荐文章于 2023-10-10 17:29:47 发布
本文介绍了一个简单的HTML页面,通过JavaScript实现两个可移动div元素之间的碰撞检测。当一个div靠近另一个div时,背景色会发生变化,直观地展示碰撞效果。
420

被折叠的 条评论
为什么被折叠?



