直接附代码:
<!DOCTYPE html>
<head>
<style>
#div1, #div2 {
width: 100px;
height: 100px;
position: fixed;
border-radius: 50px;
}
#div1 {
left: 500px;
background-color: blue;
}
#div2 {
left: 700px;
background-color: red;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script>
window.onload = function() {
var $div1 = document.getElementById('div1');
var $div2 = document.getElementById('div2');
drag($div1);
drag($div2);
/**
* 绑定拖拽事件
*/
function drag(obj) {
obj.onmousedown = function(evt) {
// 鼠标点击处相对于物体左上角的x,y
var disX = evt.clientX - obj.offsetLeft;
var disY = evt.clientY - obj.offsetTop;
// 鼠标移动事件绑定在鼠标按下事件内,这样就有了 按住拖动 的效果
document.onmousemove = function(evt) {
// 物体左上角相对于浏览器窗口的L(left)、T(top)
var L = evt.clientX - disX;
var T = evt.clientY - disY;
// 防止物体超出浏览器窗口
if ( L < 0 ) {
L = 0;
} else if ( L > document.documentElement.clientWidth - obj.offsetWidth ) {
L = document.documentElement.clientWidth - obj.offsetWidth;
}
if ( T < 0 ) {
T = 0;
} else if ( T > document.documentElement.clientHeight - obj.offsetHeight ) {
T = document.documentElement.clientHeight - obj.offsetHeight;
}
obj.style.left = L + 'px';
obj.style.top = T + 'px';
if (isCollision($div1, $div2)) {
console.log('碰撞')
} else {
console.log('分离')
}
}
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
}
return false;
}
}
/**
* 碰撞检测
*/
function isCollision(obj1, obj2) {
// 计算两圆心坐标
var x1 = obj1.offsetLeft + 50;
var y1 = obj1.offsetTop + 50;
var x2 = obj2.offsetLeft + 50;
var y2 = obj2.offsetTop + 50;
// 两圆碰撞条件:圆心距离小于等于两圆半径之和
return Math.sqrt(Math.pow(x1 -x2, 2) + Math.pow(y1 - y2, 2)) <= 50 + 50;
}
}
</script>
</body>
</html>
参考资料:
1、 [JS拖拽原理](https://www.cnblogs.com/moranhuishou/p/6149890.html)
2、JS基础篇--了解JS的clientX、pageX、screenX等方法来获取鼠标坐标详解
3、js随手笔记-------理解JavaScript碰撞检测算法核心简单实现原理
4、[理解SetCapture、ReleaseCapture、GetCapture](https://www.cnblogs.com/findumars/p/3907635.html)