MDN之Web API 接口參考(一)【Element.scrollIntoView()和Element.scrollTop】

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"之一。默認爲 “start”。

inline 可選
start”, “center”, “end”, 或 "nearest"之一。默認爲 “nearest”。

示例

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

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

注意

取決於其它元素的佈局情況,此元素可能不會完全滾動到頂端或底端。


Element.scrollTop

Element.scrollTop 屬性可以獲取或設置一個元素的內容垂直滾動的像素數。

一個元素的 scrollTop 值是這個元素的頂部到視口可見內容(的頂部)的距離的度量。當一個元素的內容沒有產生垂直方向的滾動條,那麼它的 scrollTop 值爲0

語法

// 獲得滾動的像素數
var  intElemScrollTop = someElement.scrollTop;

運行此代碼後, intElemScrollTop 是一個整數,即element的內容向上滾動的像素數。

// 設置滾動的距離
element.scrollTop = intValue;

scrollTop 可以被設置爲任何整數值,同時注意:

  • 如果一個元素不能被滾動(例如,它沒有溢出,或者這個元素有一個"non-scrollable"屬性), scrollTop將被設置爲0
  • 設置scrollTop的值小於0scrollTop 被設爲0
  • 如果設置了超出這個容器可滾動的值, scrollTop會被設爲最大值.

例子

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章