ViewTransition: ready 屬性

可用性有限

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

readyViewTransition 介面的一個只讀屬性,它返回一個 Promise。當偽元素樹被建立並且過渡動畫即將開始時,這個 Promise 會被 fulfilled。

如果過渡無法開始,ready 將會被 reject。這可能是由於配置錯誤造成的,例如重複的 view-transition-name,或者傳遞給 Document.startViewTransition() 的回撥函式丟擲異常或返回一個被 reject 的 Promise。

一個 Promise。

示例

在下面的示例中,ready 用於觸發一個自定義的圓形展開檢視過渡,該過渡從使用者點選時的游標位置開始,動畫由 Web Animations API 提供。

js
// Store the last click event
let lastClick;
addEventListener("click", (event) => (lastClick = event));

function spaNavigate(data) {
  // Fallback for browsers that don't support this API:
  if (!document.startViewTransition) {
    updateTheDOMSomehow(data);
    return;
  }

  // Get the click position, or fallback to the middle of the screen
  const x = lastClick?.clientX ?? innerWidth / 2;
  const y = lastClick?.clientY ?? innerHeight / 2;
  // Get the distance to the furthest corner
  const endRadius = Math.hypot(
    Math.max(x, innerWidth - x),
    Math.max(y, innerHeight - y),
  );

  // Create a transition:
  const transition = document.startViewTransition(() => {
    updateTheDOMSomehow(data);
  });

  // Wait for the pseudo-elements to be created:
  transition.ready.then(() => {
    // Animate the root's new view
    document.documentElement.animate(
      {
        clipPath: [
          `circle(0 at ${x}px ${y}px)`,
          `circle(${endRadius}px at ${x}px ${y}px)`,
        ],
      },
      {
        duration: 500,
        easing: "ease-in",
        // Specify which pseudo-element to animate
        pseudoElement: "::view-transition-new(root)",
      },
    );
  });
}

此動畫還需要以下 CSS,以關閉預設 CSS 動畫並阻止舊檢視和新檢視狀態以任何方式混合(新狀態“擦拭”舊狀態,而不是過渡進入)

css
::view-transition-image-pair(root) {
  isolation: auto;
}

::view-transition-old(root),
::view-transition-new(root) {
  animation: none;
  mix-blend-mode: normal;
  display: block;
}

規範

規範
CSS 檢視過渡模組第 1 級
# dom-viewtransition-ready

瀏覽器相容性

另見