JS 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 可选

一个包含下列属性的对象:

  1. behavior 可选
    定义动画过渡效果, "auto"或 “smooth” 之一。默认为 “auto”。
  2. block 可选
    定义垂直方向的对齐, “start”, “center”, “end”, 或 "nearest"之一。默认为 “start”。
  3. 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"});

注意

取决于其它元素的布局情况,此元素可能不会完全滚动到顶端或底端。

猜你喜欢

转载自blog.csdn.net/qq_36658051/article/details/117353233