Element.scrollIntoView() 元素滚动
使用scrollIntoView方法,添加滚动行为。设置"smooth "属性实现平滑的滚动动画。
滚动到顶部
const scrollToTop = scrollEle => scrollEle.scrollIntoView({ behavior: "smooth", block: "start" })。
滚动到底部
const scrollToBottom = scrollEle => scrollELE.scrollIntoView({ behavior: "smooth", block: "end" })。
Element.scrollIntoView()
Element 接口的scrollIntoView()方法会滚动元素的父容器,使被调用scrollIntoView()的元素对用户可见。语法
element.scrollIntoView(); // 等同于element.scrollIntoView(true) element.scrollIntoView(alignToTop); // Boolean型参数 element.scrollIntoView(scrollIntoViewOptions); // Object型参数
参数
alignToTop可选- 一个
Boolean值:- 如果为
true,元素的顶端将和其所在滚动区的可视区域的顶端对齐。相应的scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是这个参数的默认值。 - 如果为
false,元素的底端将和其所在滚动区的可视区域的底端对齐。相应的scrollIntoViewOptions: {block: "end", inline: "nearest"}。
- 如果为
scrollIntoViewOptions可选- 一个包含下列属性的对象:
behavior可选- 定义动画过渡效果,
"auto"或"smooth"之一。默认为"auto"。 block可选- 定义垂直方向的对齐,
"start","center","end", 或"nearest"之一。默认为"start"。 inline可选- 定义水平方向的对齐,
"start","center","end", 或"nearest"之一。默认为"nearest"。
示例
var element = document.getElementById("box");
element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
注意
取决于其它元素的布局情况,此元素可能不会完全滚动到顶端或底端。
参考文献: https://developer.mozilla.org/zh-CN/docs/web/api/element/scrollintoview

浙公网安备 33010602011771号