实现后效果:
![](https://img2018.cnblogs.com/blog/1834003/202002/1834003-20200220220038741-2105620908.gif)
- 实现原理:
- 在允许拖拽的节点元素上,监听mousedown(按下鼠标按钮)事件,鼠标按下后,事件触发
- 监听mousemove(鼠标移动)事件,修改克隆出来的节点的坐标,实现节点跟随鼠标的效果
- 监听mouseup(放开鼠标按钮)事件,将原节点克隆到鼠标放下位置的容器里,将绑定的mousemove和mouseup事件清除掉,拖拽完成。
拖拽方法实现
//鼠标拖拽方法
function drag(e) {
var event = e || window.event; //事件兼容
var disX = event.clientX - this.offsetLeft, //当前鼠标在区块上的横向相对位置
disY = event.clientY - this.offsetTop; //当前鼠标在区块上的纵向相对位置
var that = this;
//鼠标移动
document.onmousemove = function (e) {
var newLeft = e.clientX - disX,
newTop = e.clientY - disY;
that.style.left = newLeft + 'px';
that.style.top = newTop + 'px';
}
//鼠标键弹起
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
HTML部分
<!DOCTYPE html>
<html>
<head>
<title>模拟重力场运动(碰撞检测&拖拽)</title>
<style>
div{
position: absolute;
left: 0;
top: 0;
100px;
height: 100px;
background-color: orange;
border-radius: 50%;
cursor: pointer;
}
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
var oDiv = document.getElementsByTagName('div')[0];
oDiv.onmousedown = drag; //拖拽事件绑定
</script>
</body>
</html>