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;
}

結果

滾動以檢視正方形元素的動畫。

規範

規範
滾動驅動動畫
# 滾動符號

瀏覽器相容性

另見