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-startanimation-range-end, 所以我们也可以在 @keyframes 中指定两组不同的关键帧, 分别对应 animation-range-startanimation-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);
  }
}

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

谢谢你看到这里😊

相关推荐
还在忙碌的吴小二2 分钟前
在 Mac 上安装并通过端口调用 Chrome DevTools MCP Server(谷歌官方 MCP 服务器)
服务器·前端·chrome·macos·chrome devtools
灵感__idea7 小时前
Hello 算法:贪心的世界
前端·javascript·算法
GreenTea9 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
killerbasd10 小时前
牧苏苏传 我不装了 4/7
前端·javascript·vue.js
吴声子夜歌11 小时前
ES6——二进制数组详解
前端·ecmascript·es6
码事漫谈11 小时前
手把手带你部署本地模型,让你Token自由(小白专属)
前端·后端
ZC跨境爬虫11 小时前
【爬虫实战对比】Requests vs Scrapy 笔趣阁小说爬虫,从单线程到高效并发的全方位升级
前端·爬虫·scrapy·html
爱上好庆祝11 小时前
svg图片
前端·css·学习·html·css3
王夏奇12 小时前
python中的__all__ 具体用法
java·前端·python
大家的林语冰12 小时前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js