详解Element.scrollIntoView()

Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。

1.语法

element.scrollIntoView(); // 等同于element.scrollIntoView(true) 
element.scrollIntoView(alignToTop); // Boolean型参数 
element.scrollIntoView(scrollIntoViewOptions); // Object型参数

2.参数

  • 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"

3.示例

var element = document.getElementById("box");

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({
    
    block: "end"});
element.scrollIntoView({
    
    behavior: "smooth", block: "end", inline: "nearest"});

4.注意

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

5.浏览器兼容性

兼容性
【参考资料】:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

猜你喜欢

转载自blog.csdn.net/a1056244734/article/details/107765008