此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Element.scrollLeft

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

Element.scrollLeft 属性可以读取或设置元素滚动条到元素左边的距离。

注意如果这个元素的内容排列方向(direction)是rtl (right-to-left) ,那么滚动条会位于最右侧(内容开始处),并且scrollLeft值为 0。此时,当你从右到左拖动滚动条时,scrollLeft 会从 0 变为负数。

警告: 在使用显示比例缩放的系统上,scrollLeft 可能会是一个小数。

scrollLeft 可以是任意整数,然而:

  • 如果元素不能滚动(比如:元素没有溢出),那么scrollLeft 的值是 0。
  • 如果给scrollLeft 设置的值小于 0,那么scrollLeft 的值将变为 0。
  • 如果给scrollLeft 设置的值大于元素内容最大宽度,那么scrollLeft 的值将被设为元素最大宽度。

示例

HTML

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

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

CSS

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

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

JavaScript

js
const button = document.getElementById("slide");

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

结构

规范

Specification
CSSOM View Module
# dom-element-scrollleft

浏览器兼容性

参见