给大家分享一个用原生JS实现拖拽元素时与另个一元素碰撞检测的小Demo,效果如下:
实现代码如下, 欢迎大家复制粘贴。
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现拖拽元素时与另个一元素碰撞检测</title>
<style>
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
z-index: 2;
}
#div2 {
width: 100px;
height: 100px;
background: yellow;
position: absolute;
left: 230px;
top: 220px;
z-index: 1;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1');
var oDiv2 = document.getElementById('div2');
// 鼠标按下时
oDiv.onmousedown = function (ev) {
var oEvent = ev || event;
var disX = oEvent.clientX - oDiv.offsetLeft;
var disY = oEvent.clientY - oDiv.offsetTop;
// 鼠标移动时
document.onmousemove = function (ev) {
var oEvent = ev || event;
oDiv.style.left = oEvent.clientX - disX 'px';
oDiv.style.top = oEvent.clientY - disY 'px';
var l1 = oDiv.offsetLeft;
var r1 = oDiv.offsetLeft oDiv.offsetWidth;
var t1 = oDiv.offsetTop;
var b1 = oDiv.offsetTop oDiv.offsetHeight;
var l2 = oDiv2.offsetLeft;
var r2 = oDiv2.offsetLeft oDiv2.offsetWidth;
var t2 = oDiv2.offsetTop;
var b2 = oDiv2.offsetTop oDiv2.offsetHeight;
// 碰撞检测的规则
if (r1 < l2 || l1 > r2 || b1 < t2 || t1 > b2) {
// 如果没有碰到
oDiv2.style.background = 'yellow';
} else {
// 如果碰到了
oDiv2.style.background = 'green';
}
};
// 鼠标抬起时
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
};
};
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>