javascript平滑滚动Element.scrollIntoView()

2019-05-243843次阅读javascript

在了解JavaScript的平滑滚动Element.scrollIntoView()之前,你要知道还有一个原生的CSS功能:scroll-behavior

 

Element.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 可选 

一个带有选项的object:

{
    behavior: "auto"  | "instant" | "smooth",
    block:    "start" | "end",
}

behavior 可选

定义缓动动画, "auto", "instant", 或 "smooth" 之一。默认为 "auto"。

block 可选

"start", "center", "end", 或 "nearest"之一。默认为 "center"。

inline 可选

"start", "center", "end", 或 "nearest"之一。默认为 "nearest"。

浏览器兼容

示例

document.querySelector("#comments").scrollIntoView({behavior:"smooth",block: "start", inline: "nearest"});

其它javascript平滑滚动方法

// Scroll to specific values
// scrollTo is the same
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

smooth scroll behavior polyfill

上一篇: vue router之后如何回到顶部  下一篇: vue中实现锚点定位及跳转  

javascript平滑滚动Element.scrollIntoView()相关文章