特定の要素の座標を取得するには、次のとおり getBoundingClientRect() を使用する。
let {left,top} = document.querySelector(element_selector).getBoundingClientRect()
これは、特定の要素の位置をブラウザの表示領域の左上を(0, 0)として、そこからの相対位置で示されています。
特定の要素の位置を取得したいとき、html の領域がブラウザの表示領域と一致していない場合などがあり、正確な値を取得できないケースがたまにある。
そういった場合も含めて、次のとおりに取得するのが良い。
function getAbsolutePosition(elm) { const {left,top} = elm.getBoundingClientRect(); const {left: bleft,top: btop} = document.body.getBoundingClientRect(); return {left: left - bleft,top: top - btop,}; } let myelmposition; myelmposition = getAbsolutePosition(elm); console.log myelmposition.left; console.log myelmposition.top;