CSS 滚动驱动动画 scroll-timeline ( scroll-timeline-name ❤️ scroll-timeline-axis )

scroll-timeline ( scroll-timeline-name ❤️ scroll-timeline-axis )

scroll() 的最后我们遇到了因为定位问题导致滚动效果失效的情况, 当然 CSS 允许我们手动指定滚动容器, 也就是哪个容器来提供 scroll progress timeline. 我们需要在提供时间线的滚动容器上声明 scroll-timeline 属性.

再次重温 scroll progress timeline, 这个时间线(timeline)是通过滚动容器(scroller)上下或左右方向的滚动推进的. 开始滚动的位置表示时间线处在 0%, 滚动结束的位置表示时间线 100%. 如果 0%100% 的位置相同, 比如容器根本不滚动, 那么时间线不会推动.

解决问题

下面的代码是不生效, 原因很简单, 当 scroll() 采用默认值时, 其第一个默认参数是 nearest, 这时就会寻找离当前元素最近的父级滚动元素. 你可能以为是 .scroll, 但实际上不是.

因为在寻找滚动元素的时候需要这个滚动元素能够影响当前元素的位置和大小, 又因为当前元素的 positionabsolute, 所以可以影响其位置和大小的元素要么是 body, 要么是 positionstatic 的元素. 换言之, 最终找到的就是 .relative, 而 .relative 根本不会滚动, 所以我们不论怎么滑动 .scroll 都不会看到任何变化.

html 复制代码
<div class="relative">
  <div class="scroll">
    <div class="absolute"></div>
  </div>
</div>
css 复制代码
.relative {
  position: relative;
}
.absolute {
  position: absolute;
  animation: bg-color linear;
  animation-timeline: scroll();
}

修改之后

css 复制代码
.scroll {
  scroll-timeline: --youHaveToBeThis;
}
.absolute {
  /* animation-timeline: scroll(); */
  animation-timeline: --youHaveToBeThis;
}

语法

animation-timeline 实际上包括 animation-timeline-nameanimation-timeline-axis 的简写属性, 后者是可选的.

如果同时制定两个值, 那么顺序一定是先 animation-timeline-nameanimation-timeline-axis

animation-timeline-name

  • none: 没有名字
  • 自定义名称: 其定义名称必须以 -- 开头. 这样可以避免与 CSS 关键字冲突.

animation-timeline-axis

可选的值是 block(默认值), inline, y, x, 具体的意思可以参考 scroll().

如果滚动容器在 animation-timeline-axis 方向上没有内容溢出, 或者溢出被隐藏, 那么将不会创建对应的时间线

谢谢你看到这里😊

相关推荐
一袋米扛几楼9810 分钟前
【网络安全】SIEM -Security Information and Event Management 工具是什么?
前端·安全·web安全
小陈工21 分钟前
2026年4月7日技术资讯洞察:下一代数据库融合、AI基础设施竞赛与异步编程实战
开发语言·前端·数据库·人工智能·python
Cobyte30 分钟前
3.响应式系统基础:从发布订阅模式的角度理解 Vue2 的数据响应式原理
前端·javascript·vue.js
竹林81833 分钟前
从零到一:在React前端中集成The Graph查询Uniswap V3池数据实战
前端·javascript
Mintopia41 分钟前
别再迷信"优化":大多数性能问题根本不在代码里
前端
倾颜41 分钟前
接入 MCP,不一定要先平台化:一次 AI Runtime 的实战取舍
前端·后端·mcp
军军君0143 分钟前
Three.js基础功能学习十八:智能黑板实现实例五
前端·javascript·vue.js·3d·typescript·前端框架·threejs
恋猫de小郭44 分钟前
Android 上为什么主题字体对 Flutter 不生效,对 Compose 生效?Flutter 中文字体问题修复
android·前端·flutter
Moment1 小时前
AI全栈入门指南:一文搞清楚NestJs 中的 Controller 和路由
前端·javascript·后端
禅思院1 小时前
前端架构演进:基于AST的常量模块自动化迁移实践
前端·vue.js·前端框架