Codog

关注微信公众号:Codog代码狗

0%

Element的scrollIntoView方法

经常遇到要将某个元素滚动到可视区域的需求,除了个别需要使用js进行复杂的定位计算外,原生js的scrollIntoView方法可以满足大部分场景了,基础的直接调用Element.scrollIntoView()方法外,还提供了更细粒度的滚动控制。

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

alignToTop: Boolean值,默认为true,顶端对齐;false的话则为底端对齐。

scrollIntoViewOptions对象有三个属性值:

  • behavior: 定义过渡动画效果,smooth则为平滑滚动,默认auto。css的scroll-behavior也可以影响滚动效果

  • block: 定义垂直方向对齐方式。”start”, “center”, “end”, 或 “nearest”之一。默认为 “start”。

  • inline: 定义水平方向对齐方式。”start”, “center”, “end”, 或 “nearest”之一。默认为 “nearest”。

MDN: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView