The difference between getBoundingClientRect (). Top and offsetTop?

What is the difference between getBoundingClientRect (). top and offsetTop?

https://codepen.io/anon/pen/bWZWQg

const elem = document.querySelector('#find');

console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top);

console.log('offsetTop: ' + elem.offsetTop);

// Stuff to push the div down the page
<div id='find'>Find me</div>

From my quick test, the only difference seems to be the number of decimal places returned.

+6
source share
2 answers

This gives you an offset relative to your client viewport, meaning that if you scroll the item and see, then you can check the difference. pen

console.log('offsetTop: ' + elem.offsetTop); //This is fixed.

console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top); // this is changing while scroll

see pen, scroll through the list and check the console.

+2
source

The HTMLElement.offsetTopread-only property returns the distance from the current element relative to the vertex offsetParent node.

getBoundingClientRect() - , - , , , .

+2

All Articles