LoginSignup
20
20

More than 5 years have passed since last update.

マウスイベントの座標取得について

Posted at

mousedown, mousemove, mouseup などのイベントで拾えるマウス座標ですが、いくつか種類があります。いつもどれがどれだったか忘れてしまうので、いい加減覚えようと思ってまとめました。

clientX, clientY

DOMコンテンツ内のX,Y座標。

HTMLページ内のワールド座標です。左上が0,0

offsetX, offsetY

イベントをハンドリングしているDOM要素内のX,Y座標。

screenX, screenY

スクリーン上のX,Y座標。

デュアルモニター環境だったりするととても大きな値になったりします。

x,y

Chromeだと使える。値はclientX, clientYと一緒。

迷った時の確認用コード

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <div style="margin: 100px; width:200px; height:2000px; border: solid 1px gray;" id="box"></div>
  <script>
    document.getElementById('box').onmousemove = function(e) {
      console.log('client(%s, %s) offset(%s, %s) screen(%s, %s)',e.clientX, e.clientY, e.offsetX, e.offsetY, e.screenX, e.screenY);
    }
  </script>
</body>

</html>

黒い枠線のボックス上でマウスを移動するとコンソールにそれぞれの座標値が出力されます。

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