css hover 离开时没有过渡怎么办_在默认状态声明 transition

17次阅读

hover离开时过渡失效,是因为transition必须写在默认状态而非:hover中;若只在:hover声明,移出时因起始态无transition而无动画;需确保起始态声明transition且覆盖所有变化属性。

css hover 离开时没有过渡怎么办_在默认状态声明 transition

hover 离开时过渡失效,是因为没在默认状态写 transition

csstransition 必须写在「起始状态」上,也就是非 :hover 的默认样式里。如果只在 :hover 中加 transition,鼠标移出时浏览器会直接跳回原样式,没有过渡效果。

transition 写在 :hover 里为什么不行

因为 :hover 是「目标状态」,而过渡动画需要从「当前状态」平滑变化到「目标状态」。移出时,浏览器要从 hover 状态变回默认状态——此时默认状态若没声明 transition,就按「无过渡」处理。

  • ✅ 正确:默认状态有 transition: background-color 0.3s ease;
  • ❌ 错误:只在 :hover 里写 transition,默认状态完全没它
  • ⚠️ 注意:transition 不会自动继承或反向生效,必须显式存在于起始态

哪些属性需要统一声明 transition 才能双向过渡

只要你想让「进入 hover」和「离开 hover」都有过渡,就必须确保:起始态(默认)和结束态(:hover)都修改了同一组可过渡属性,并且起始态已声明 transition

  • 常见可过渡属性:colorbackground-colortransformopacitywidth/height(需有明确初始值)
  • 不可过渡属性:displayposition(值变化类型不连续)、font-size(单位混用如 empx 可能中断)
  • 推荐写法:transition: all 0.2s ease; 或精确控制:transition: background-color 0.2s, transform 0.2s;

一个最小可运行示例

button {   background-color: #007bff;   color: white;   padding: 8px 16px;   border: none;   /* ✅ transition 必须在这里声明 */   transition: background-color 0.25s ease, transform 0.2s ease; } 

button:hover { background-color: #0056b3; transform: scale(1.05); }

如果删掉默认状态里的 transition,移出时 transform 和背景色都会瞬间回弹。

立即学习前端免费学习笔记(深入)”;

最容易被忽略的是:过渡是否覆盖了所有你实际修改的属性。比如加了 transform 却只在 transition 里写了 color,那缩放依然会突变。

text=ZqhQzanResources