實現這個功能主要是配合鼠標的mouse事件,拖動原理以下圖(以橫向x座標爲例,y軸原理是同樣的):html
html代碼:java
<div id="box"></div>
CSS代碼:spa
#box { position: absolute; width: 100px; height: 100px; top: 10px; left: 10px; background: red; }
javaScript代碼:code
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; } }