HTML DOM Element scrollTop attribute

Definition and Usage

scrollTop Sets or returns the number of pixels the element content is vertically scrolled.

See also:

scrollLeft attribute

Propriedade overflow do CSS

Evento onscroll

Example

Example 1

Get the pixel number of the content scrolled for "myDIV":

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

亲自试一试

Example 2

Roll the content of "myDIV" horizontally to 50 pixels and vertically to 10 pixels:

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

亲自试一试

Example 3

Roll the content of "myDIV" horizontally by 50 pixels and vertically by 10 pixels:

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

亲自试一试

例子 4

将 <body> 的内容水平滚动 30 像素,垂直滚动 10 像素:

const html = document.documentElement;
html.scrollLeft += 30;
html.scrollTop += 10;

亲自试一试

例子 5

在不同滚动位置的类名之间切换 - 当用户从页面顶部向下滚动 50 像素时,类名 "test" 将被添加到元素中(并在再次向上滚动时删除):

window.onscroll = function() {myFunction()};
function myFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("myP").className = "test";
  }
    document.getElementById("myP").className = "";
  }
}

亲自试一试

例子 6

当用户从页面顶部向下滚动 350 像素时滑入一个元素(添加 slideUp 类):

window.onscroll = function() {myFunction()};
function myFunction() {
  if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
    document.getElementById("myImg").className = "slideUp";
  }
}

亲自试一试

语法

返回 scrollTop 属性:

element.scrollTop

设置 scrollTop 属性:

element.scrollTop = pixels

属性值

描述
pixels

元素内容垂直滚动的像素数。

  • 如果该数字为负数,则该数字设置为 0。
  • 如果元素无法滚动,则该数字设置为 0。
  • 如果该数大于允许的最大值,则将该数设置为最大值。

返回值

类型 描述
数字 元素内容垂直滚动的像素数。

浏览器支持

所有浏览器都支持 element.scrollTop

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Suporte Suporte Suporte Suporte Suporte Suporte