440
443

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-21

要素をドラッグして移動することは、JavaScriptにおいて頻出パターンです。
しかし、それを簡単に実現するコードは意外と知られていません。

画像をドラッグするとグリグリ動かせるコード
<img id="$img" src="https://js.cx/clipart/ball.svg" width="40" height="40">
<script>
$img.onpointermove = function(event){
    if(event.buttons){
        this.style.left     = this.offsetLeft + event.movementX + 'px'
        this.style.top      = this.offsetTop  + event.movementY + 'px'
        this.style.position = 'absolute'
        this.draggable      = false
        this.setPointerCapture(event.pointerId)
    }
}
</script>

mousedown+mousemove+mouseup+フラグ変数を駆使して実現するコードはよくありますが複雑になるので、ドラッグするだけなら上記コードを使いましょう。

440
443
3

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
440
443

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?