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

浏览器兼容性

另见