使用scrollIntoView()方法
先看示例:
示例
goAnchor(id) {
let maodian = document.getElementById(id).scrollIntoView();
maodian
.querySelector(selector)
.scrollIntoView({
behavior: "smooth", //动画过渡效果
block: "start", //垂直方向的对齐
inline: "start", //水平方向的对齐
});
maodian.querySelector(selector).scrollIntoView(false);
},
Element 接口的 scrollIntoView() 方法会滚动元素的父容器,使被调用 scrollIntoView() 的元素对用户可见。
语法
scrollIntoView()
scrollIntoView(alignToTop)
scrollIntoView(scrollIntoViewOptions)
Copy to Clipboard
参数
-
alignToTop可选一个布尔值:
- 如果为
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。
-