Element:scrollTop 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Element 接口的 scrollTop 属性用于获取或设置元素内容从其顶部边缘滚动的像素数。在现代浏览器中,此值是亚像素精度的,这意味着它不一定是整数。

一个双精度浮点值,表示元素当前从原点垂直滚动的像素数,正值表示元素向下滚动(以显示更多底部内容)。如果元素根本没有上下滚动,则 scrollTop 为 0。如果文档不是活动文档,则返回值为 0。如果文档是在亚像素精度设备上渲染的,则返回值也是亚像素精度的,可能包含小数部分。

如果元素可以从初始包含块向上滚动,那么 scrollTop 可能为负值。例如,如果元素的 flex-directioncolumn-reverse 并且内容向上增长,则当滚动条位于最底部位置(滚动内容的开头)时,scrollTop0,然后随着您滚动到内容末尾而变得越来越负。

Safari 会通过将 scrollTop 更新到最大滚动位置(除非禁用了默认的“反弹”效果,例如通过将 overscroll-behavior 设置为 none)来响应过度滚动,而 Chrome 和 Firefox 则不会。例如,在 Safari 中,仅通过在元素已位于顶部时继续向上滚动,scrollTop 就可能为负值。

可以设置 scrollTop 属性,这将导致元素滚动到指定的垂直位置,其方式与使用具有 behavior: "auto"Element.scroll() 相同。

示例

滚动元素

在此示例中,尝试滚动带有虚线的边框的容器,并观察 scrollTop 值如何变化。

HTML

html
<div id="container">
  <p>
    Far out in the uncharted backwaters of the unfashionable end of the western
    spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this
    at a distance of roughly ninety-two million miles is an utterly
    insignificant little blue green planet whose ape-descended life forms are so
    amazingly primitive that they still think digital watches are a pretty neat
    idea.
  </p>
</div>

<div id="output">scrollTop: 0</div>

CSS

css
#container {
  overflow: scroll;
  height: 150px;
  width: 150px;
  border: 5px dashed orange;
}

#output {
  padding: 1rem 0;
}

JavaScript

js
const container = document.querySelector("#container");
const output = document.querySelector("#output");

container.addEventListener("scroll", (event) => {
  output.textContent = `scrollTop: ${container.scrollTop}`;
});

结果

规范

规范
CSSOM 视图模块
# dom-element-scrolltop

浏览器兼容性

另见