HTML DOM scrollTop Property

元素对象参考手册Element Object

Examples

Scroll the scrollbar to get the distance from the element's scrollbar to the left or top of the element:

const element = document.getElementById("myDIV"); let x = elmnt.scrollLeft; let y = elmnt.scrollTop;

Try it yourself »

Definition and Usage

The scrollTop property can get or set the number of pixels that an element's content is vertically scrolled.

An element's scrollTop value is a measure of the distance from the top of the element's content (rolled up) to the top of its visible viewport content. When an element's content does not produce a vertical scrollbar, its scrollTop value is 0.

On systems using display scaling, scrollTop may provide a decimal number.


Browser Support

Property
scrollTop Yes Yes Yes Yes Yes

Syntax

Get the scrollTop property value:

// 获得滚动的像素数
var intElemScrollTop = element.scrollTop 

intElemScrollTop is an integer, that is, the number of pixels the element's content is scrolled upward.

Set the scrollLeft property value:

// 设置滚动的距离
element.scrollTop = intValue;

scrollTop can be any integer, however:

  • If an element cannot be scrolled (for example, it has no overflow, or the element has a "non-scrollable"attribute),scrollTopwill be set to0。
  • SettingscrollTopthe value to less than 0,scrollTopis set to0
  • If a value is set that exceeds the scrollable range of this container,scrollTopit will be set to the maximum value.

Technical Details

Return Value: Returns an integer representing the number of pixels the element's content is vertically scrolled.

More Examples

Example

Set the element with ID "myDIV" to scroll 50 pixels horizontally and 10 pixels vertically:

const element = document.getElementById("myDIV"); element.scrollLeft = 50; element.scrollTop = 10;

Try it yourself »

Example

Set the element with ID "myDIV" to scroll 50 pixels horizontally and 10 pixels vertically each time the button is clicked:

var elmnt = document.getElementById("content"); function getFunction() { var x = elmnt.scrollWidth; var y = elmnt.scrollHeight; } function setFunction() { elmnt.style.height = y.scrollHeight + "px"; elmnt.style.width = y.scrollWidth + "px"; }

Try it yourself »


元素对象参考手册Element Object

Other Extensions