Get the number of pixels the content of "myDIV" is scrolled:
const element = document.getElementById("myDIV");
let x = elmnt.scrollLeft;
let y = elmnt.scrollTop;
Try it Yourself »
Scroll the contents of "myDIV" TO 50 pixels horizontally and 10 pixels vertically:
const element = document.getElementById("myDIV");
element.scrollLeft = 50;
element.scrollTop = 10;
Try it Yourself »
Scroll the contents of "myDIV" BY 50 pixels horizontally and 10 pixels vertically:
const element = document.getElementById("myDIV");
element.scrollLeft += 50;
element.scrollTop += 10;
Try it Yourself »
More examples below.
The scrollTop
property sets or returns the number of pixels an element's content is scrolled vertically.
Return the scrollTop property:
element.scrollTop
Set the scrollTop property:
element.scrollTop =
pixels
Value | Description |
pixels | The number of pixels the element's content is scrolled vertically. If the number is negative, the number is set to 0. If the element cannot be scrolled, the number is set to 0. If the number is greater than maximum allowed, the number is set to the maximum. |
Type | Description |
Number | The number of pixels the element's content is scrolled vertically. |
Scroll the contents of <body> by 30 pixels horizontally and 10 pixels vertically:
const html = document.documentElement;
html.scrollLeft += 30;
html.scrollTop += 10;
Try it Yourself »
Toggle between class names on different scroll positions - When the user scrolls down 50 pixels from the top of the page, the class name "test" will be added to an element (and removed when scrolled up again):
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Try it Yourself »
Slide in an element when the user has scrolled down 350 pixels from the top of the page (add the slideUp class):
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
document.getElementById("myImg").className = "slideUp";
}
}
Try it Yourself »
element.scrollTop
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!