JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop Example</title>
</head>
<body>
<div id="drag-element" draggable="true" style="width: 100px; height: 100px; background-color: red; position: absolute; top: 50px; left: 50px;"></div>
<p>Mouse position: <span id="mouse-position"></span></p>
<script>
const dragElement = document.getElementById("drag-element");
const mousePosition = document.getElementById("mouse-position");
dragElement.addEventListener("dragstart", function() {
// dragover イベントならドラッグ中のカーソルの位置が FireFox でも取得できる
// window に dragover イベントを登録しておくことで画面中のどこにカーソルがあってもカーソルの位置を取得できる
window.addEventListener("dragover", handleDragover);
function handleDragover(event) {
const currentMouseX = event.clientX;
const currentMouseY = event.clientY;
mousePosition.innerHTML = "X: " + currentMouseX + ", Y: " + currentMouseY;
}
// dragend イベントで dragstart した時に追加したイベントハンドラーを掃除する
dragElement.addEventListener("dragend", dragCleanUp);
function dragCleanUp() {
window.removeEventListener('dragover', handleDragover);
dragElement.removeEventListener('dragend', dragCleanUp);
}
});
</script>
</body>
</html>