scroll()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

scroll() CSS 函数 可以与 animation-timeline 一起使用,以指示可滚动元素(滚动器)和滚动条轴,从而为当前元素的动画提供一个匿名的滚动进度时间轴。滚动进度时间轴通过滚动滚动器在顶部和底部(或左侧和右侧)之间进行推进。滚动范围中的位置被转换为进度百分比——从 0% 开始到 100% 结束。

注意: 如果指定的轴不包含滚动条,则动画时间轴将不活动(进度为零)。

注意: 每次使用 scroll() 都对应于 Web Animations APIScrollTimeline 的一个独特实例。

语法

css
/* Function with no parameters set */
animation-timeline: scroll();

/* Values for selecting the scroller element */
animation-timeline: scroll(nearest); /* Default */
animation-timeline: scroll(root);
animation-timeline: scroll(self);

/* Values for selecting the axis */
animation-timeline: scroll(block); /* Default */
animation-timeline: scroll(inline);
animation-timeline: scroll(y);
animation-timeline: scroll(x);

/* Examples that specify scroller and axis */
animation-timeline: scroll(block nearest); /* Default */
animation-timeline: scroll(inline root);
animation-timeline: scroll(x self);

参数

滚动器

用于指示将提供滚动进度时间轴的滚动器元素的值可以是以下任何一种

最近

当前元素最近的祖先元素,该祖先元素在任一轴上都有滚动条。这是默认值。

文档的根元素。

self

当前元素本身。

滚动条轴值可以是以下任何一种

block

滚动容器的块轴上的滚动条,该轴的方向垂直于行内文本的流向。对于水平书写模式(例如标准英语),这与 y 相同,而对于垂直书写模式,则与 x 相同。这是默认值。

inline

滚动容器的行内轴上的滚动条,该轴的方向平行于行内文本的流向。对于水平书写模式,这与 x 相同,而对于垂直书写模式,则与 y 相同。

y

滚动容器的垂直轴上的滚动条。

x

滚动容器的水平轴上的滚动条。

注意: 滚动器和轴的值可以按任何顺序指定。

正式语法

<scroll()> = 
scroll( [ <scroller> || <axis> ]? )

<scroller> =
root |
nearest |
self

<axis> =
block |
inline |
x |
y

示例

设置匿名的滚动进度时间轴

在此示例中,#square 元素使用匿名的滚动进度时间轴进行动画,该时间轴通过 scroll() 函数应用于要动画的元素。此特定示例中的时间轴由最近的具有(任何)滚动条的父元素提供,来自块方向的滚动条。

HTML

示例的 HTML 如下所示。

html
<div id="container">
  <div id="square"></div>
  <div id="stretcher"></div>
</div>

CSS

下面的 CSS 定义了一个正方形,它根据 animation-timeline 属性提供的时间轴以交替方向旋转。在此例中,时间轴由 scroll(block nearest) 提供,这意味着它将选择最近的祖先元素(具有滚动条)的块方向的滚动条;在此例中是“container”元素的垂直滚动条。

注意: blocknearest 实际上是默认参数值,因此我们也可以只使用 scroll()

css
#square {
  background-color: deeppink;
  width: 100px;
  height: 100px;
  margin-top: 100px;
  position: absolute;
  bottom: 0;

  animation-name: rotateAnimation;
  animation-duration: 1ms; /* Firefox requires this to apply the animation */
  animation-direction: alternate;
  animation-timeline: scroll(block nearest);
}

@keyframes rotateAnimation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

容器的 CSS 将其高度设置为 300px,并且我们还将容器设置为在溢出时创建垂直滚动条。“stretcher”CSS 将块高度设置为 600px,这会强制容器元素溢出。这两者共同确保容器具有垂直滚动条,这使其可以用作匿名滚动进度时间轴的来源。

css
#container {
  height: 300px;
  overflow-y: scroll;
  position: relative;
}

#stretcher {
  height: 600px;
}

结果

滚动以查看正方形元素的动画。

规范

规范
滚动驱动动画
# 滚动符号

浏览器兼容性

另见