文件:startViewTransition() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

Document 介面的 startViewTransition() 方法會啟動一個新的同文檔 (SPA) 檢視過渡,並返回一個 ViewTransition 物件來表示它。

呼叫 startViewTransition() 時,會遵循 檢視過渡過程 中所述的一系列步驟。

語法

js
startViewTransition()
startViewTransition(updateCallback)
startViewTransition(options)

引數

updateCallback 可選

一個可選的回撥函式,通常在 SPA 檢視過渡過程中呼叫以更新 DOM,它會返回一個 Promise。在 API 捕獲當前頁面快照後呼叫此回撥。當回撥返回的 Promise fulfilled 時,檢視過渡將在下一幀開始。如果回撥返回的 Promise rejected,則過渡將被放棄。

options 可選

一個包含用於配置檢視過渡的選項的物件。它可以包含以下屬性:

update 可選

上面描述的相同的 updateCallback 函式。預設為 null

types 可選

一個字串陣列。這些字串充當過渡的類名或識別符號,允許你根據發生的過渡型別選擇性地應用 CSS 樣式或執行不同的 JavaScript 邏輯。預設為空序列。

返回值

一個 ViewTransition 物件例項。

示例

使用同文檔檢視過渡

在此同文檔檢視過渡中,我們檢查瀏覽器是否支援檢視過渡。如果不支援,我們會使用一種回退方法設定背景顏色,該方法會立即應用。否則,我們可以安全地呼叫 document.startViewTransition() 並使用我們在 CSS 中定義的動畫規則。

html
<main>
  <section></section>
  <button id="change-color">Change color</button>
</main>

我們使用 ::view-transition-group 偽元素將 animation-duration 設定為 2 秒。

css
html {
  --bg: indigo;
}
main {
  display: flex;
  flex-direction: column;
  gap: 5px;
}
section {
  background-color: var(--bg);
  height: 60px;
  border-radius: 5px;
}
::view-transition-group(root) {
  animation-duration: 2s;
}
js
const colors = ["darkred", "darkslateblue", "darkgreen"];
const colBlock = document.querySelector("section");
let count = 0;
const updateColour = () => {
  colBlock.style = `--bg: ${colors[count]}`;
  count = count !== colors.length - 1 ? ++count : 0;
};
const changeColor = () => {
  // Fallback for browsers that don't support View Transitions:
  if (!document.startViewTransition) {
    updateColour();
    return;
  }

  // With View Transitions:
  const transition = document.startViewTransition(() => {
    updateColour();
  });
};
const changeColorButton = document.querySelector("#change-color");
changeColorButton.addEventListener("click", changeColor);
changeColorButton.addEventListener("keypress", changeColor);

如果支援檢視過渡,點選按鈕將在 2 秒內將顏色從一種過渡到另一種。否則,背景顏色將使用回退方法設定,沒有任何動畫。

規範

規範
CSS 檢視過渡模組第 1 級
# dom-document-startviewtransition
CSS 檢視過渡模組級別 2
# dom-document-startviewtransition

瀏覽器相容性

另見