Phần tử HTML DOM cuộnTop
Ví dụ
Lấy số pixel nội dung của "myDIV" được cuộn:
const element = document.getElementById("myDIV");
let x = elmnt.scrollLeft;
let y = elmnt.scrollTop;
Hãy tự mình thử »Cuộn nội dung của "myDIV" TO 50 pixel theo chiều ngang và 10 pixel theo chiều dọc:
const element = document.getElementById("myDIV");
element.scrollLeft = 50;
element.scrollTop = 10;
Hãy tự mình thử »Cuộn nội dung của "myDIV" BY 50 pixel theo chiều ngang và 10 pixel theo chiều dọc:
const element = document.getElementById("myDIV");
element.scrollLeft += 50;
element.scrollTop += 10;
Hãy tự mình thử »Thêm ví dụ dưới đây.
Sự miêu tả
Thuộc tính scrollTop
đặt hoặc trả về số pixel mà nội dung của phần tử được cuộn theo chiều dọc.
Cú pháp
Trả về thuộc tính ScrollTop:
element .scrollTop
Đặt thuộc tính ScrollTop:
element .scrollTop = pixels
Giá trị tài sản
Value | Description |
pixels |
The number of pixels the element's content is scrolled vertically. If the number is negative, the number is set to 0. If the element cannot be scrolled, the number is set to 0. If the number is greater than maximum allowed, the number is set to the maximum. |
Giá trị trả về
Kiểu | Sự miêu tả |
Con số | Số pixel nội dung của phần tử được cuộn theo chiều dọc. |
Thêm ví dụ
Ví dụ
Cuộn nội dung của <body> 30 pixel theo chiều ngang và 10 pixel theo chiều dọc:
const html = document.documentElement;
html.scrollLeft += 30;
html.scrollTop += 10;
Hãy tự mình thử »Ví dụ
Chuyển đổi giữa các tên lớp trên các vị trí cuộn khác nhau - Khi người dùng cuộn xuống 50 pixel từ đầu trang, tên lớp "test" sẽ được thêm vào một thành phần (và bị xóa khi cuộn lên lại):
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Hãy tự mình thử »Ví dụ
Trượt vào một phần tử khi người dùng đã cuộn xuống 350 pixel từ đầu trang (thêm lớp slideUp):
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
document.getElementById("myImg").className = "slideUp";
}
}
Hãy tự mình thử »Hỗ trợ trình duyệt
element.scrollTop
được hỗ trợ trong tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |