在JavaScript中,可以使用window.scrollTo和element.scrollIntoView方法来实现平滑滚动页面或元素到顶部或底部。
- 使用
window.scrollTo:
// 滚动到页面顶部
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
});
// 滚动到页面底部
window.scrollTo({
top: document.body.scrollHeight,
left: 0,
behavior: 'smooth'
});- 使用
element.scrollIntoView:
// 滚动元素到页面顶部
document.querySelector('#yourElementId').scrollIntoView({
behavior: 'smooth',
block: 'start'
});
// 滚动元素到页面底部
document.querySelector('#yourElementId').scrollIntoView({
behavior: 'smooth',
block: 'end'
});其中#yourElementId是你想滚动到页面顶部或底部的元素的ID。scrollIntoView方法接受一个配置对象,其中behavior: 'smooth'表示平滑滚动,block属性可以是'start'(元素的顶部将和其所在滚动区的可视区域顶部对齐)或者是'end'(元素的底部将和其所在滚动区的可视区域底部对齐)。