See the Pen ball-area by s4i (@s4i) on CodePen.
HTML部分
<div class="outer">
<img id="$img" src="https://js.cx/clipart/ball.svg" width="40" height="40">
</div>
CSS部分
.outer {
user-select: none;
width: 200px;
height: 200px;
border: 3px solid blue;
}
JavaScript部分
$img.onpointermove = function (e) {
if (e.buttons) {
//親要素内に留める
let pe = e.currentTarget.parentElement;
if (
pe.offsetTop > this.offsetTop + e.movementY ||
pe.offsetLeft + pe.offsetWidth <
this.offsetLeft + this.offsetWidth + e.movementX ||
pe.offsetTop + pe.offsetHeight <
this.offsetTop + this.offsetHeight + e.movementY ||
pe.offsetLeft > this.offsetLeft + e.movementX
) {
return;
}
this.style.left = this.offsetLeft + e.movementX + "px";
this.style.top = this.offsetTop + e.movementY + "px";
this.style.position = "absolute";
this.draggable = false;
this.setPointerCapture(e.pointerId);
}
};