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

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

谢谢你看到这里😊

相关推荐
kingwebo'sZone4 分钟前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_090123 分钟前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农35 分钟前
Vue 2.3
前端·javascript·vue.js
夜郎king1 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
夏幻灵2 小时前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_2 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝2 小时前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions2 小时前
2026年,微前端终于“死“了
前端·状态模式
万岳科技系统开发2 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
程序员猫哥_3 小时前
HTML 生成网页工具推荐:从手写代码到 AI 自动生成网页的进化路径
前端·人工智能·html