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

Chrome中CSS点击驱动动画无法重复运行的问题求助

Chrome中details元素动画仅首次生效的问题解决办法

问题原因

这是Chrome的特性而非Bug:当<details>元素第一次打开时,动画正常执行;但关闭后再次打开,Chrome不会重置动画的播放状态——因为动画属性未发生变化,浏览器判定动画已完成过一次,不会重新触发。而Firefox会自动处理状态切换时的动画重置逻辑。

解决方案

根据你的使用场景,提供两种可行方案:

方案1:改用CSS Transition(推荐,更简洁)

如果你的动画只是简单的属性过渡,用transition替代animation更适配Chrome的行为,每次<details>状态切换时,属性值变化都会触发过渡:

.details-content {
  opacity: 0;
  transform-origin: top right;
  transform: translateY(-16px) scaleY(.9);
  transition: opacity 300ms ease-out, transform 300ms ease-out;
}

details[open] .details-content {
  opacity: 1;
  transform: translateY(0) scaleY(1);
}
<details>
 <summary>This is summary</summary>
 <div class="details-content">This is hidden content</div>
</details>

方案2:用JavaScript强制重置动画(保留animation的场景)

如果必须使用CSS Animation,可以监听<details>的toggle事件,强制重置动画属性并触发浏览器重绘,让Chrome重新播放动画:

@keyframes menu-animation {
  0% {
    opacity: 0;
    transform-origin: top right;
    transform: translateY(-16px) scaleY(.9);
  }
  100% {
    opacity: 1;
    transform-origin: top right;
    transform: translateY(0) scaleY(1);
  }
}

details:not([open]) .details-content {
  opacity: 0;
  transform: translateY(-16px) scaleY(.9);
}

details[open] .details-content {
  animation: 300ms ease-out 0s 1 normal forwards menu-animation;
}
<details>
 <summary>This is summary</summary>
 <div class="details-content">This is hidden content</div>
</details>
document.querySelectorAll('details').forEach(details => {
  details.addEventListener('toggle', () => {
    if (details.open) {
      const content = details.querySelector('.details-content');
      // 先移除动画属性
      content.style.animation = 'none';
      // 强制浏览器重绘
      void content.offsetWidth;
      // 恢复动画属性
      content.style.animation = '';
    }
  });
});

补充说明

原代码仅定义了动画的0%关键帧,建议补全100%状态,让动画的起始、结束状态更明确,避免浏览器自动推断结束状态带来的兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:33:20