本文介绍如何利用 CSS 滚动驱动动画(Scroll-driven Animations)实现:Cookie 栏默认紧贴视口底部,仅当用户滚动至页面最底部时,才动态添加 50px 的 margin-bottom,避免遮挡内容或提前触发。
本文介绍如何利用 css 滚动驱动动画(scroll-driven animations)实现:cookie 栏默认紧贴视口底部,仅当用户滚动至页面最底部时,才动态添加 50px 的 `margin-bottom`,避免遮挡内容或提前触发。
在构建网页时,常需将 Cookie 同意横幅(如
传统 JavaScript 监听 scroll 事件虽可实现,但存在性能开销与重绘抖动风险。现代方案推荐使用 CSS 滚动驱动动画(Scroll-driven Animations) —— 一种声明式、高性能的原生方案,通过 animation-timeline: scroll() 将动画绑定到滚动进度。
以下为完整实现(需 Chrome 115+ 或支持 @scroll-timeline 的浏览器):
#cookie-section {
min-height: 50px;
width: 100%;
position: fixed;
bottom: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(38, 38, 38, 0.9);
color: #fff;
padding: 0 20px;
/* 关键:启用滚动驱动动画 */
animation: margin-bottom-increase 1s forwards;
animation-timeline: scroll(root);
animation-range: 90% 100%; /* 从滚动位置90%开始,到100%完成 */
}
@keyframes margin-bottom-increase {
from { margin-bottom: 0; }
to { margin-bottom: 50px; }
}
/* 确保页面有足够高度用于测试滚动 */
body {
min-height: 300vh;
margin: 0;
}
<section id="cookie-section"><span id="cookie-text">我们使用 Cookie 来提升您的浏览体验</span> </section>
? 关键要点说明:
- animation-range: 90% 100% 表示:当滚动进度达到文档总高度的 90% 时开始动画,100% 时完成(即刚好触底),精准控制触发时机;
- animation-timeline: scroll(root) 指定以整个页面(root scroller)为滚动上下文;
- forwards 保证动画结束后样式保持 margin-bottom: 50px,避免回退;
- 使用 inset: auto 0 0(等价于 top: auto; right: 0; bottom: 0;)可替代 bottom: 0,语义更清晰,但非必需。
⚠️ 注意事项:
- 当前兼容性有限:Chrome 115+ 原生支持,Firefox 和 Safari 尚未实现(截至 2024 年中)。生产环境务必添加渐进增强或降级方案(如 JS 监听 scroll + getBoundingClientRect() 判断是否临近底部);
- 若页面高度不足(如 高度小于视口),滚动无法触发,此时无需添加 margin-bottom,符合预期;
- 避免对 fixed 元素使用 margin-bottom 以外的布局属性(如 height 变化)触发重排,本例仅改变外边距,性能友好。
综上,滚动驱动动画提供了优雅、声明式的解决方案,代表了 Web 动画的未来方向。在目标浏览器可控的前提下(如企业内网、Chrome-only 应用),强烈推荐采用;面向大众用户的站点,则建议结合 @supports 特性检测 + JavaScript 回退逻辑,兼顾体验与兼容性。










