實現原理
1、給目標div增加鼠標按下事件,記錄下div對象的位置(left,top)和鼠標點擊的位置(x,y)
2、監聽鼠標移動事件,在移動過程中計算出鼠標的移動位置(nx,xy),然後實時計算出鼠標從點擊到現在的偏移量,然後再將div的位置修改,這樣就實現了div位置的變動
ps:目標div的屬性position要設置absolute或者relative
3、div可以移動了,但什麼時候停止移動呢?當然是鼠標彈起的時候,所以我們監聽鼠標彈起的事件,並結束移動
代碼實現
<title>div-drag-每天一個知識點/<title><style>
.dragable {
width: 200px;
height: 200px;
border: 1px solid darkorchid;
position: relative;
}
var dragDiv = document.querySelector(".dragable");
dragDiv.addEventListener("mousedown", function(e) {
//獲取div初始位置對象
var divRect = dragDiv.getBoundingClientRect();
//獲取鼠標點擊的位置
var downX = e.clientX;
var downY = e.clientY;
//開關打開
var startMove = true;
//設置樣式為移動光標
dragDiv.style.cursor = "move";
window.onmousemove = function(e) {
if (!startMove) {
return;
}
let newLeft = e.clientX - downX + divRect.left;
let newTop = e.clientY - downY + divRect.top;
dragDiv.style.left = newLeft + "px";
dragDiv.style.top = newTop + "px";
return false;
};
window.onmouseup = function(e) {
//結束移動
startMove = false;
dragDiv.style.cursor = "default";
return false;
};
e.stopPropagation();
});
代碼手敲可運行
當然這個實現還有很多可擴展或者不足,比如怎麼限制div移動的範圍,能力有限,在以後的日子裡會嘗試編寫js組件,實現更完善的功能。
閱讀更多 景柯學 的文章