scrollIntoViewOptions是非常有用的,但是目前隻有Chrome和FireFox可以支援,但是可以通過其他插件實作(smoothscroll-polyfill)
示例
document.getElementById('content').scrollIntoView({
block: 'start',
inline: 'nearest',
behavior: 'smooth'
})
文檔
第一種方案:方法參數傳 “alignToTop”
目前之前這個參數得到了良好的支援
scrollIntoView(alignToTop); // Boolean parameter
alignToTop
一個Boolean值:
- 如果為true,元素的頂端将和其所在滾動區的可視區域的頂端對齊。
- 如果為false,元素的底端将和其所在滾動區的可視區域的底端對齊。
true :元素的頂部将對齊到可滾動祖先的可見區域的頂部。對應于scrollIntoViewOptions: {block: "start", inline: "nearest"} 這是預設值
false:元素的底部将與可滾動祖先的可見區域的底部對齊。對應于scrollIntoViewOptions: {block: "end", inline: "nearest"}。
使用
document.getElementById('content').scrollIntoView(true);
第二種方案(如示例):方法參數傳 “scrollIntoViewOptions”
目前這個參數浏覽器對它的支援并不好,可以檢視下文相容性
element.scrollIntoView(scrollIntoViewOptions); // Object parameter
behavior: [可選]定義過渡動畫。"auto","instant"或"smooth"。預設為"auto"。
block :[可選] "start"(頂部),"center"(居中),"end"(尾部) 或"nearest"。預設為"center"。
inline:[可選] "start","center","end"或"nearest"。預設為"nearest"。
使用
document.getElementById('content').scrollIntoView({
block: 'start',
inline: 'nearest',
behavior: 'smooth'
})