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

滚动时设无效值未让CSS属性恢复初始值的问题排查

问题原因

当通过scroll-driven动画(View Timeline)设置自定义属性值时,Chrome对无效值的处理逻辑与用户交互(如:hover)场景存在差异:

  • 在:hover场景中,设置--bit:1后,animation-play-state: var(--bit, paused)会因1是无效值,自动回退到属性初始值running;
  • 但在scroll-driven动画中,浏览器会将整数1视为合法的自定义属性值,即使它对animation-play-state无效,也不会回退到初始值,而是持续保留之前的fallback值paused,导致动画无法启动。

解决方案

将scroll-driven动画中设置的--bit值改为字符串类型的'1',而非整数1。此时:

  1. 背景色的calc(var(--bit,0)*100%)会自动将字符串'1'转换为数字1,正常计算颜色过渡;
  2. animation-play-state: var(--bit, paused)会判定字符串'1'为无效值,触发属性回退到初始值running,动画正常启动。

修改后的完整代码:

* { margin: 0 }

header, section {
  display: grid;
  place-items: center; 
  height: 100vh
}

section {
  animation: b linear both;
  animation-timeline: view();
  animation-range: entry 100% entry 100%
}

/* 修改为字符串类型的'1' */
@keyframes b { to { --bit: '1' } }

div {
  width: 9em;
  aspect-ratio: 1;
  background: 
    color-mix(in hsl, hotpink calc(var(--bit, 0)*100%), gold);
  animation: rot 2s linear infinite;
  animation-play-state: var(--bit, paused)
}

@keyframes rot { to { rotate: 1turn } }
<header>
  <h2>Scroll!</h2>
</header>
<section>
  <div></div>
</section>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:45:27