How to get the distance of an element from the top

In JavaScript, you can use the offsetTop property to get the distance from the top of an element. Here is an example:

const element = document.getElementById("myElement");
const distanceToTop = element.offsetTop;
console.log(distanceToTop);

In the above code, we first obtain a specific element through document.getElementById("myElement") (assuming its id is "myElement"), and then use the offsetTop property to obtain the distance of the element from the top.

offsetTop returns a distance relative to the top edge of the nearest positioned parent element (statically positioned, relative positioned, or absolutely positioned). If there is no positioned parent element, it returns the distance relative to the top of the document.

It should be noted that the value of offsetTop is an integer representing the distance in pixels. If the element to be retrieved is not visible (for example, display: none or visibility: hidden is set), offsetTop will return 0. Additionally, if you want to get the distance relative to the top of the window instead of the top of the document, you can use the getBoundingClientRect().top method.

To sum up, the offsetTop attribute can help us get the distance from the top of an element and perform corresponding operations when needed.

getBoundingClientRect().top method:

const element = document.getElementById("myElement");
const distanceToTop = element.getBoundingClientRect().top;
console.log(distanceToTop);

In the above code, we first obtain a specific element through document.getElementById("myElement") (assuming its id is "myElement" here), and then use the getBoundingClientRect() method to obtain the position information object of the element. Next, we can extract the top property from the position information object, which represents the distance of the element relative to the top of the viewport.

The getBoundingClientRect() method returns a DOMRect object, which contains the position and size information of the element, including attributes such as top, right, bottom, and left.

It should be noted that getBoundingClientRect().top returns a relative value in pixels. If the element is not displayed or is hidden (for example, if display: none or visibility: hidden is set), then a value will be returned regardless of the distance from the top of the viewport.

Use the getBoundingClientRect().top method to obtain the distance of an element relative to the top of the viewport, and perform further operations if necessary, such as determining whether the element is visible, triggering scrolling, etc.

Guess you like

Origin blog.csdn.net/weixin_43534452/article/details/132210671