Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính scrollTop trong HTML DOM

Thuộc tính scrollTop trong HTML DOM trả về và cho phép thay đổi số pixel nội dung đã được cuộn dọc (vertically) của một phần tử trong tài liệu HTML.

Cú pháp

Lấy giá trị scrollTop

element.scrollTop

Thiết lập giá trị scrollTop

element.scrollTop = value

Ở đây value tính bằng pixel.

Ví dụ

Ví dụ sử dụng thuộc tính scrollTop (và scrollLeft):

<!DOCTYPE html>
<html>
<head>
<style>
  body { text-align: center; color: #fff; background: #ff7f5094; height: 100%; }
  p { font-weight: 700; font-size: 1.8rem; height: 80px; overflow: auto; width: 150px; margin: 20px auto; }
  .btn { background: #0197F6; border: none; height: 2rem; border-radius: 2px; width: 35%; margin: 2rem auto; display: block; color: #fff; outline: none; cursor: pointer; }
  .show { font-size: 1.5rem; }
  #myDIV { height: 200px; width: 200px; overflow: auto; margin: 20px auto; }
  #content { height: 400px; width: 1000px; background-color: lightblue; }
</style>
</head>
<body>
<h1>Demo thuộc tính scrollLeft/scrollTop DOM</h1>
<div id="myDIV" onscroll="display()">
  <div id="content"></div>
</div>
<div class="show"></div>
<script>
  function display() {
    var elmnt = document.getElementById("myDIV");
    var x = elmnt.scrollLeft;
    var y = elmnt.scrollTop;
    document.querySelector(".show").innerHTML = "Cuộn dọc = " + y + "px Cuộn ngang = " + x + "px";
  }
</script>
</body>
</html>

Kết quả

Cuộn bên trong hộp màu xanh dương để lấy giá trị cuộn dọc và cuộn ngang.