实现这个功能主要是配合鼠标的mouse事件,拖动原理如下图(以横向x坐标为例,y轴原理是一样的):
html代码:
<div id="box"></div>
CSS代码:
#box { position: absolute; width: 100px; height: 100px; top: 10px; left: 10px; background: red; }
javaScript代码:
let box = document.getElementById('box'); document.onmousedown = function (e) { let disx = e.pageX - box.offsetLeft; let disy = e.pageY - box.offsetTop; document.onmousemove = function (e) { box.style.left = e.pageX - disx + 'px'; box.style.top = e.pageY - disy + 'px'; } //释放鼠标按钮,将事件清空,否则始终会跟着鼠标移动 document.onmouseup = function () { document.onmousemove = document.onmouseup = null; } }