CSS 滚动驱动动画与 @keyframes 新语法

CSS 滚动驱动动画与 @keyframes

在 CSS 滚动驱动动画相关的属性出来之后, @keyframes 也迎来变化.

以前, @keyframes 的值可以是 from, to, 或者百分数. 现在它多了一种属性的值 <timeline-range-name> <percentage>

建议先了解 animation-range 不然你会对 timeline-range-name 感到陌生.

例子

我们先看看在新语法出现之前怎么写的. 我们用 from(也就是 0%) 表示动画开始祯, to(100%) 表示动画结束祯

html 复制代码
<div class="scroller">
  Lorem ...
  <div class="box"></div>
  Lorem ....
</div>
css 复制代码
.scroller {
  height: 250px;
  overflow: auto;
}
.box {
  animation: grow both;
  animation-timeline: view();
}
@keyframes grow {
  from {
    transform: scaleX(0);
  }
  to {
    transform: scaleX(1);
  }
}

如何使用新语法呢? 你会发现 from 其实对应的就是 entry 0% 的位置, to 对应的是 exit 100% 的位置, 于是

css 复制代码
@keyframes grow {
  entry 0% {
    transform: scaleX(0);
  }
  exit 100% {
    transform: scaleX(1);
  }
}

📖 <timeline-range-name> 后面的百分比不能省略.

另一种 animation-range 的实现

有了新的语法, 我们大胆尝试通过 @keyframes 修改关键帧, 来达到修改 animation-range 的想法. 比如我希望实现 animation-range: entry

css 复制代码
.box {
  animation: grow both;
  animation-timeline: view();
}
@keyframes grow {
  entry 0% {
    transform: scaleX(0);
  }
  entry 100% {
    transform: scaleX(1);
  }
}

因为 animation-range 是一个简写属性, 包括 animation-range-start 和 animation-range-end, 所以我们也可以在 @keyframes 中指定两组不同的关键帧, 分别对应 animation-range-start 和 animation-range-end.

css 复制代码
@keyframes grow {
  entry 0% {
    transform: scaleX(0);
  }
  entry 100% {
    transform: scaleX(1);
  }
  exit 0% {
    transform: scaleX(1);
  }
  exit 100% {
    transform: scaleX(2);
  }
}

请大家注意动图右下角的代码

谢谢你看到这里😊

相关推荐
夕水15 分钟前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
狗头大军之江苏分军1 小时前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬1 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月2 小时前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端
xurileidian2 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
掘金安东尼3 小时前
更多审查智能体,更少盲区:GitHub Copilot 代码审查是怎么做的
前端·github copilot
Hilaku5 小时前
2026 年了,jQuery 真的该死了吗?
前端·javascript·程序员
zach5 小时前
吃透 React setState 同步异步之谜:从批量更新、事件循环到版本演进的完整拆解
前端·react.js
不服老的小黑哥5 小时前
02-从 pnpm dev 到 Spring Boot 启动:后端服务到底怎么跑起来?
前端
htzyl2065 小时前
javaScript——this 的四种绑定:为什么箭头函数改不了它
前端·javascript