2018-2020 js tinh khiết:
Có một cách rất thuận tiện để cuộn đến phần tử:
el.scrollIntoView({
behavior: 'smooth', // smooth scroll
block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})
Nhưng theo tôi hiểu thì anh ta không có sự hỗ trợ tốt như các lựa chọn dưới đây.

Tìm hiểu thêm về phương pháp.
Nếu cần thiết là phần tử nằm ở trên cùng:
const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset
window.scrollTo({
top: topPos, // scroll so that the element is at the top of the view
behavior: 'smooth' // smooth scroll
})
Ví dụ trình diễn trên Codepen
Nếu bạn muốn phần tử nằm ở trung tâm:
const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scroll({
top: rect.top + rect.height / 2 - viewHeight / 2,
behavior: 'smooth' // smooth scroll
});
Ví dụ trình diễn trên Codepen
Ủng hộ:

Họ viết đó scroll
là phương pháp tương tự nhưscrollTo
, nhưng hỗ trợ cho thấy tốt hơn trong scrollTo
.
Thêm về phương pháp
<a href="#anchorName">link</a>