元素:scrollIntoView() 方法

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

* 此特性的某些部分可能存在不同級別的支援。

Element 介面的 scrollIntoView() 方法滾動元素的祖先容器,使呼叫 scrollIntoView() 的元素對使用者可見。

語法

js
scrollIntoView()
scrollIntoView(alignToTop)
scrollIntoView(options)

引數

alignToTop 可選

一個布林值。

  • 如果為 true,元素的頂部將與可滾動祖先的可見區域的頂部對齊。相當於 scrollIntoViewOptions: {block: "start", inline: "nearest"}。這是預設值。
  • 如果為 false,元素的底部將與可滾動祖先的可見區域的底部對齊。相當於 scrollIntoViewOptions: {block: "end", inline: "nearest"}
options 可選

具有以下屬性的物件:

behavior 可選

確定滾動是即時發生還是平滑動畫。其值可以是以下之一:

  • smooth:滾動應該平滑動畫。
  • instant:滾動應該即時發生,一次性跳轉。
  • auto:滾動行為由 scroll-behavior 的計算值決定。

預設值為 auto

block 可選

定義元素在可滾動祖先容器中的垂直對齊方式。其值可以是以下之一:

  • start:將元素的上邊緣與可滾動容器的頂部對齊,使元素在垂直方向上出現在可見區域的起始位置。
  • center:將元素在垂直方向上居中對齊到可滾動容器的中心,使其定位在可見區域的中間。
  • end:將元素的下邊緣與可滾動容器的底部對齊,使元素在垂直方向上出現在可見區域的末尾。
  • nearest:將元素滾動到垂直方向上最近的邊緣。如果元素更靠近可滾動容器的頂部邊緣,它將對齊到頂部;如果更靠近底部邊緣,它將對齊到底部。這會最小化滾動距離。

預設值為 start

container 可選

定義可滾動祖先容器。其值可以是以下之一:

  • all:所有可滾動容器都會受到影響(包括視口)。
  • nearest:只有最近的可滾動容器會受到滾動的影響。

預設值為 all

inline 可選

定義元素在可滾動祖先容器中的水平對齊方式。其值可以是以下之一:

  • start:將元素的左邊緣與可滾動容器的左側對齊,使元素在水平方向上出現在可見區域的起始位置。
  • center:將元素在水平方向上居中對齊到可滾動容器的中心,使其定位在可見區域的中間。
  • end:將元素的右邊緣與可滾動容器的右側對齊,使元素在水平方向上出現在可見區域的末尾。
  • nearest:將元素滾動到水平方向上最近的邊緣。如果元素更靠近可滾動容器的左邊緣,它將對齊到左側;如果更靠近右邊緣,它將對齊到右側。這會最小化滾動距離。

預設值為 nearest

返回值

無(undefined)。

示例

使用 scrollIntoView()

js
const element = document.getElementById("box");

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

控制頂部/底部對齊

預設情況下,元素對齊到可滾動祖先的頂部(或底部)邊緣。要定義自定義間距,請使用 scroll-margin-topscroll-margin-bottom。當頁面上有固定標題時,這通常很有用。

HTML

html
<body>
  <header class="navbar">Navbar</header>
  <main class="content">
    <button id="go-to-bottom">Go to bottom</button>
    <button id="go-to-top">Go to top</button>
  </main>
</body>

CSS

css
.navbar {
  height: 50px;
  position: sticky;
  top: 0;
  border-bottom: 1.5px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}
.content {
  height: 2000px;
  position: relative;
}
#go-to-bottom {
  position: absolute;
  top: 10px;
  /* Without this, the button will be aligned to the top of the page
  instead of bottom of navbar when scrolled */
  scroll-margin-top: 60px;
}
#go-to-top {
  position: absolute;
  bottom: 10px;
  scroll-margin-bottom: 0;
}

JavaScript

js
const goToTop = document.getElementById("go-to-top");
const goToBottom = document.getElementById("go-to-bottom");
goToBottom.addEventListener("click", () => {
  goToTop.scrollIntoView({ behavior: "instant", block: "end" });
});
goToTop.addEventListener("click", () => {
  goToBottom.scrollIntoView({ behavior: "instant", block: "start" });
});

結果

規範

規範
CSSOM 檢視模組
# dom-element-scrollintoview

瀏覽器相容性

另見