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

如何实现输入框失去焦点时反向播放CSS聚焦动画?

解决CSS输入框聚焦/失焦的双向冲刷动画问题

我明白你的问题所在了——你已经实现了输入框聚焦时的白色冲刷动画,但失焦时直接跳回栗色,完全没有反向的过渡效果。下面我来帮你搞定这个双向动画的需求:

完整代码示例

@keyframes search-transition {
  0% { background: maroon; }
  20% { background: linear-gradient(to left, maroon 0%, whitesmoke 40%, whitesmoke 60%, maroon 100%); }
  40% { background: linear-gradient(to left, maroon 0%, white 30%, whitesmoke 70%, maroon 100%); }
  60% { background: linear-gradient(to left, maroon 0%, whitesmoke 20%, whitesmoke 80%, maroon 100%); }
  80% { background: linear-gradient(to left, maroon 0%, whitesmoke 10%, whitesmoke 90%, maroon 100%); }
  100% { background: whitesmoke; }
}

input {
  border: none;
  background: maroon;
}

input:focus {
  outline: none;
  /* 播放正向动画,结束后保持whitesmoke状态 */
  animation: search-transition 0.1s forwards;
}

input:not(:focus) {
  /* 播放反向动画,从whitesmoke过渡回maroon,结束后保持maroon状态 */
  animation: search-transition 0.1s reverse forwards;
}
<input type="text" />

关键改进点说明

  • 复用动画+反向播放:只写一套动画逻辑,通过animation-direction: reverse直接实现失焦时的反向冲刷效果,不用重复写两套几乎一样的@keyframes代码,更简洁。
  • 移除冲突的固定背景色:删掉了你原来在:focus里写的background: whitesmoke,让动画完全掌控背景状态,避免静态背景色覆盖动画效果。
  • 用forwards锁定最终状态:确保动画结束后停在目标状态——聚焦后保持whitesmoke,失焦后保持maroon,不会出现状态跳变。

额外优化建议

如果担心页面刚加载时,input:not(:focus)的反向动画会导致不必要的闪屏(其实实际不会,因为初始背景已经是maroon,动画过程和初始状态重叠,肉眼看不到),可以加一点JS辅助,只在输入框被聚焦过一次后才触发失焦动画:

const input = document.querySelector('input');
input.addEventListener('focus', () => {
  input.classList.add('has-focused');
});

然后修改对应的CSS:

input.has-focused:not(:focus) {
  animation: search-transition 0.1s reverse forwards;
}

这样初始状态下不会触发任何额外动画,只有输入框被点击过一次后,失焦时才会播放反向的红色冲刷效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:59:09