Код выглядит следующим образом:
const getOffset = el => {
const { left, top } = el.getBoundingClientRect()
const { scrollTop, scrollLeft } = document.body
return { top: top + scrollTop, left: left + scrollLeft }
}
использовать:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<div style="display: flex;align-items:center;justify-content:center;width: 100vw;height: 100vh;">
<div id="ruben" style="width: 100px;height: 100px;background-color: red;"></div>
</div>
<body>
<script type="application/javascript">
const getOffset = el => {
const { left, top } = el.getBoundingClientRect()
const { scrollTop, scrollLeft } = document.body
return { top: top + scrollTop, left: left + scrollLeft }
};
window.onresize = e => {
console.table(getOffset(document.getElementById('ruben')))
}
</script>
</body>
</html>
Перетаскиваем размер окна