Get the offsetTop position of "myDIV":
const element = document.getElementById("myDIV");
let pos = element.offsetTop;
Try it Yourself »
Get the positions of "myDIV":
const element = document.getElementById("test");
Let pos1 = element.offsetTop;
let pos2 = element.offsetLeft;
Try it Yourself »
More examples below.
The offsetTop
property returns the top position (in pixels) relative to the parent.
The returned value includes:
The offsetTop
property is read-only.
All block-level elements report offsets relative to the offset parent:
The offset parent is the nearest ancestor that has a position other than static.
If no offset parent exists, the offset is relative to the document body.
Return the top offset position:
element.offsetTop
Type | Description |
Number | The top position of the element, in pixels. |
Create a sticky navigation bar:
// Get the navbar
const navbar = document.getElementById("navbar");
// Get the offset position of the navbar
const sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
Try it Yourself »
element.offsetTop
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!