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
を使う方法もあるが、スマホで問題があるとのこと。