Movatterモバイル変換


[0]ホーム

URL:


LoginSignup
445

Go to list of users who liked

445

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScriptで要素をドラッグして移動する簡単な方法

Last updated atPosted at 2024-02-21

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

画像をドラッグするとグリグリ動かせるコード
<imgid="$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=falsethis.setPointerCapture(event.pointerId)}}</script>

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

445

Go to list of users who liked

445
4

Go to list of comments

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
445

Go to list of users who liked

445

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?


[8]ページ先頭

©2009-2025 Movatter.jp