Scroll the content by 100 pixels, and alert the scrollX and scrollY:
window.scrollBy(100, 100);
alert(window.scrollX + window.scrollY);
Try it Yourself »
More examples below.
The scrollX
property returns the pixels a document has scrolled from the upper left corner of the window.
The scrollX
property is read-only.
The scrollX
property is equal to the pageXOffset
property.
For cross-browser compatibility, use window.pageXOffset instead of window.scrollX.
window.scrollX
scrollX
Type | Description |
A number | The number of pixels the document has scrolled from the upper left corner of the window. |
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.scrollY >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
Try it Yourself »
window.scrollX
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!