2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「JavaScriptで要素をドラッグして移動する簡単な方法」という記事を見たが、何となく外枠が欲しくなった

Last updated at Posted at 2024-02-29

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);
  }
};
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?