javascript で要素の絶対座標(オフセット)を取得する

例えば下記の a タグが存在していて、
それの座標(オフセット)を取得したい時。

<a name="sample"></a>

その1

  • 単純に要素のトップのY座標を取得する時は offsetTop
let target = document.querySelector('a[name=sample]');
console.log(target.offsetTop)

その2

  • 要素の底辺の座標などちょっと特殊な座標を調べたい時は getBoundingClientRect() がいいかもしれない
let target = document.querySelector('a[name=sample]');
let offsets = target.getBoundingClientRect();
console.log(offsets)

getBoundingClientRect() について、ページをスクロールした際には、
その現在の座標が起点になるので値はスクロール位置によって変わる。
そのため window.pageYOffset, window.pageXOffset が必要

let target = document.querySelector('a[name=sample]');
let offsets = target.getBoundingClientRect();
// 要素のY座標を取得する
console.log(window.pageYOffset + offsets.y)
カテゴリー:js