LoginSignup
11
9

More than 5 years have passed since last update.

Chrome Devtoolsで要素の位置を調べる方法

Posted at

Elementsパネルで要素を特定できたけど、その要素がどこに表示されているのか分からないという場合がある。そんなときはconsoleペインで下記を実行すると位置情報を表示できる。

> $0.getBoundingClientRect()
DOMRect {x: 319.5, y: 356.5, width: 33, height: 46, top: 356.5, …}

$0 は自動的にセットされる変数で「最後に検証された要素」を表す。

x, y, top, bottom, right, leftはビューポート(現在の表示領域)の左上を(0, 0)とした相対座標。
これをページ内の絶対座標に変換するには下記のようにするのが良いらしい(getBoundingClientRect()を使って要素のページ内座標を取得するよい方法):

function getAbsolutePosition(elm){
  const {left, top} = elm.getBoundingClientRect();
  const {left: bleft, top: btop} = document.body.getBoundingClientRect();
  return {
    left: left - bleft,
    top: top - btop,
  };
}

window.offsetX window.offsetY を使う方法もあるが、スマホで問題があるとのこと。

11
9
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
11
9