Element.scrollLeft - Web APIs 编辑

The Element.scrollLeft property gets or sets the number of pixels that an element's content is scrolled from its left edge.

If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position (at the start of the scrolled content), and then increasingly negative as you scroll towards the end of the content.

On systems using display scaling, scrollLeft may give you a decimal value.

Syntax

Getting the value

// Get the number of pixels scrolled
var sLeft = element.scrollLeft;

sLeft is an integer representing the number of pixels that element has been scrolled from the left edge.

Setting the value

// Set the number of pixels scrolled
element.scrollLeft = 10;

scrollLeft can be specified as any integer value. However:

  • If the element can't be scrolled (e.g., it has no overflow), scrollLeft is set to 0.
  • If specified as a value less than 0 (greater than 0 for right-to-left elements), scrollLeft is set to 0.
  • If specified as a value greater than the maximum that the content can be scrolled, scrollLeft is set to the maximum.

Example

HTML

<div id="container">
  <div id="content">Click the button to slide right!</div>
</div>

<button id="slide" type="button">Slide right</button>

CSS

#container {
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  overflow-x: scroll;
}

#content {
  width: 250px;
  background-color: #ccc;
}

JavaScript

const button = document.getElementById('slide');

button.onclick = function () {
  document.getElementById('container').scrollLeft += 20;
};

Result

Specifications

SpecificationStatusComment
CSS Object Model (CSSOM) View Module
The definition of 'scrollLeft' in that specification.
Working Draft

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:77 次

字数:4392

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文