HTML DOM scrollLeft Property

元素对象参考手册Element Object

Examples

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

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

Try it Yourself »

Definition and Usage

The scrollLeft property can read or set the distance from the element's scrollbar to the element's left.

Note that if the content direction of this element is rtl (right-to-left), the scrollbar will be at the far right (where the content starts), and the scrollLeft value is 0. In this case, when you drag the scrollbar from right to left, scrollLeft will change from 0 to a negative number.

On systems with display scaling, scrollLeft may be a decimal number.


Browser Support

Property
scrollLeft Yes Yes Yes Yes Yes

Syntax

Get the scrollLeft property value:

// 获取滚动条到元素左边的距离
var sLeft = element.scrollLeft 

sLeft is an integer representing how many pixels the element's scrollbar is from the element's left.

Set the scrollLeft property value:

// 设置滚动条滚动了多少像素
element.scrollLeft = pixels

scrollLeft can be any integer, however:

  • If the element cannot scroll (for example, the element has no overflow), thenscrollLeftits value is 0.
  • If you setscrollLefta value less than 0, thenscrollLeftits value will become 0.
  • If you setscrollLefta value greater than the maximum width of the element content, thenscrollLeftits value will be set to the element's maximum width.

Technical Details

Return value: Returns an integer representing the number of pixels the element's content has been horizontally 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