Я пытаюсь реализовать простейший drag and drop контроллер. Для смещения блока использую свойство события movementX/movementY. Однако, при перетаскивании на большие расстояния, мышка оказывается за пределами перетаскиваемого блока.
Вот мой код:
JS
const field = document.getElementById("field");
field.onmousedown = function () {
const targetClass = target.getAttribute("class");
document.ondragstart = () => false;
document.body.onselectstart = () => false;
field.onmousemove = function ({ movementX, movementY }) {
if (targetClass === "node") {
const [targetX] = target.style.left.match(/-?[0-9]*\.?[0-9]+/g);
const [targetY] = target.style.top.match(/-?[0-9]*\.?[0-9]+/g);
target.style.left = Number(targetX) + Number(movementX) + "px";
target.style.top = Number(targetY) + Number(movementY) + "px";
}
}
document.onmouseup = function () {
field.onmousemove = null;
field.onmouseup = null;
document.ondragstart = null;
document.body.onselectstart = null;
};
}
HTML:
<div id="field" style="transform: translate(0px, 0px) scale(1);">
<div class="node" style="left: 0px; top: 0px;"></div>
</div>
CSS:
#field {
width: 100%;
height: 100%;
visibility: visible;
position: absolute;
}
.node {
width: 100px;
height: 100px;
border: 2px solid black;
border-radius: 3%;
position: absolute;
}