被移動元素必須爲絕對定位code
position:absolute;
<div class = "move-container" > <div class = "move" style="position:absolute; width:100px; height:100px; background:gray"> </div> </div>
var moveElem = document.querySelector('.move'); //待拖拽元素 var dragging; //是否激活拖拽狀態 var tLeft, tTop; //鼠標按下時相對於選中元素的位移 //監聽鼠標按下事件 document.addEventListener('mousedown', function(e) { if (e.target == moveElem) { dragging = true; //激活拖拽狀態 var moveElemRect = moveElem.getBoundingClientRect(); tLeft = e.clientX - moveElemRect.left; //鼠標按下時和選中元素的座標偏移:x座標 tTop = e.clientY - moveElemRect.top; //鼠標按下時和選中元素的座標偏移:y座標 } }); //監聽鼠標放開事件 document.addEventListener('mouseup', function(e) { dragging = false; }); //監聽鼠標移動事件 document.addEventListener('mousemove', function(e) { if (dragging) { var moveX = e.clientX - tLeft, moveY = e.clientY - tTop; moveElem.style.left = moveX + 'px'; moveElem.style.top = moveY + 'px'; } });