ScrollTimeline

可用性有限

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

ScrollTimeline 介面是 Web Animations API 的一部分,它代表一個滾動進度時間軸(有關詳細資訊,請參閱 CSS 滾動驅動動畫)。

ScrollTimeline 例項傳遞給 Animation() 建構函式或 animate() 方法,以將其指定為控制動畫進度的時間軸。

AnimationTimeline ScrollTimeline

建構函式

ScrollTimeline()

建立一個新的 ScrollTimeline 物件例項。

例項屬性

此介面還繼承了其父級 AnimationTimeline 的屬性。

source 只讀

返回一個對可滾動元素(scroller)的引用,該元素滾動的位置正在驅動時間軸的進度,從而驅動動畫的進度。

axis 只讀

返回一個列舉值,表示正在驅動時間軸進度的滾動軸。

例項方法

此介面繼承了其父級 AnimationTimeline 的方法。

示例

顯示滾動進度時間軸的源和軸

在此示例中,我們沿檢視進度時間軸為具有 box 類的元素設定動畫——隨著文件滾動,它會在螢幕上進行動畫。我們將 source 元素和滾動 axis 輸出到右上角的 output 元素。

HTML

示例的 HTML 如下所示。

html
<div class="content"></div>
<div class="box"></div>
<div class="output"></div>

CSS

示例的 CSS 如下所示:

css
.content {
  height: 2000px;
}

.box {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: rebeccapurple;
  position: fixed;
  top: 20px;
  left: 0%;
}

.output {
  font-family: "Helvetica", "Arial", sans-serif;
  position: fixed;
  top: 5px;
  right: 5px;
}

JavaScript

在 JavaScript 中,我們獲取 boxoutput <div> 的引用,然後建立一個新的 ScrollTimeline,指定驅動滾動時間軸進度的是文件(<html>)元素,滾動軸是 block 軸。然後,我們使用 Web Animations API 為 box 元素設定動畫。最後,我們將源元素和軸顯示在 output 元素中。

js
const box = document.querySelector(".box");
const output = document.querySelector(".output");

const timeline = new ScrollTimeline({
  source: document.documentElement,
  axis: "block",
});

box.animate(
  {
    rotate: ["0deg", "720deg"],
    left: ["0%", "100%"],
  },
  {
    timeline,
  },
);

output.textContent = `Timeline source element: ${timeline.source.nodeName}. Timeline scroll axis: ${timeline.axis}`;

結果

滾動以檢視正在設定動畫的框。

規範

規範
滾動驅動動畫
# scrolltimeline-interface

瀏覽器相容性

另見