https://teratail.com/questions/4pnustw5rp458d
<!DOCTYPE html>
<meta charset="utf-8">
<title></title>
<style>
p {
border: solid 1px black;
width: 100px;
height: 100px;
margin: 0;
}
</style>
<body>
<p>drag</p>
<script>
class A {
draggable = false;
diffX = null;
diffY = null;
#init = function (e) {
['mousedown','mouseup', 'mousemove', 'mouseout'].forEach (etype=>e.addEventListener (etype, this, false));
e.draggable = false;
e.style.position = 'absolute';
};
constructor (target) {
this.target = target;
this.#init (target);
}
locate (x, y) {
let s = this.target.style;
s.top = (this.diffY + y) + 'px';
s.left = (this.diffX + x) + 'px';
}
handleEvent (event) {
switch (event.type) {
case 'mousedown':
this.draggable = true;
let { top, left } = this.target.getBoundingClientRect ();
let { clientX: mx, clientY: my} = event;
this.diffX = (left - mx) | 0;
this.diffY = (top - my) | 0;
break;
case 'mouseup' : case 'mouseout' :
this.draggable = false;
break;
case 'mousemove':
if (this.draggable) {
let { pageX: x, pageY: y} = event;
this.locate (x, y);
}
break;
}
}
}
let p = new A (document.querySelector ('p'));
//_________________
{//蛇足
let p = document.createElement ('p');
for (let i = 1; i <= 12; i++) {
let _p = p.cloneNode (true);
let x = 600 + Math.sin (360/12*i*Math.PI/180)*300;
let y = 320 - Math.cos (360/12*i*Math.PI/180)*300;
document.body.appendChild (_p).append ('drag', i);
_p.style.position = 'absolute';
_p.style.top = (y|0) + 'px';
_p.style.left = (x|0) + 'px';
new A (_p);
}
}
</script>