You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于视图的CSS animation-timeline动画无法生效,求技术支持

解决CSS animation-timeline: view() 动画不生效的问题

以下是几个关键修复点,按顺序调整后即可让动画正常运行:

1. 必须指定 animation-range

animation-timeline: view() 需要明确动画触发的视图范围,默认设置可能无法触发动画。给.wrapper添加该属性,指定元素在视图中的哪个阶段执行动画:

div.wrapper {
  width: 50%;
  height: 100vh; /* 设置为视口高度,确保元素有足够高度触发滚动交互 */
  background-color: red;
  animation: fadeIn linear;
  animation-timeline: view();
  /* 定义动画在元素顶部进入视图到完全进入视图时执行 */
  animation-range: entry 0% entry 100%;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

2. 确保页面有滚动空间

如果元素一开始就完全在视图内,没有"进入/离开视图"的过程,动画不会触发。给容器设置足够高度,让页面能滚动:

body {
  margin: 0;
}
.container {
  min-height: 200vh; /* 容器高度超过视口,产生滚动 */
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

3. 确认浏览器兼容性

animation-timeline: view() 是较新的CSS特性,仅支持Chrome 115+、Edge 115+、Safari 16.4+、Firefox 125+版本。如果浏览器版本过低,需升级后再测试。

修改后的完整代码示例

<!DOCTYPE html>
<html>
<head>
<style>
body {
  margin: 0;
}
.container {
  min-height: 200vh;
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}
div.wrapper {
  width: 50%;
  height: 100vh;
  background-color: red;
  animation: fadeIn linear;
  animation-timeline: view();
  animation-range: entry 0% entry 100%;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
</head>
<body>
<div class="container">
  <div class="wrapper">
    <h2>Sans prise de tête...</h2>
    <p class="card"></p>
    <btn class="cta"></btn>
  </div>
  <div class="wrapper">
    <h2></h2>
    <p class="card"></p>
    <btn class="cta">Plus d'infos</btn>
  </div>
</div>
</body>
</html>

现在滚动页面,就能看到每个.wrapper元素进入视图时,会从透明渐变为完全显示。

内容的提问来源于stack exchange,提问作者spots 727

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 21:18:23