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

如何实现:hover反向动画?解决鼠标移出时元素消失不流畅问题

解决元素消失时无平滑过渡的问题

当前问题:鼠标悬停在circle元素上时,square元素能正常播放显示动画,但鼠标移出shapes容器后,square会立即消失,无法实现和显示时一样的流畅动画效果。

问题原因

你仅在#shapes:hover>#square选择器中添加了transition属性,这意味着只有元素从隐藏切换到显示状态时才会应用过渡效果;而从显示切换回隐藏时,元素的默认样式里没有过渡配置,所以会直接跳变。

修复方案

将transition属性移到#square的基础样式中,让元素在任何状态变化时都应用过渡效果:

修改后的CSS代码:

body {
  margin: 100px;
}

#circle {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  background-color: black;
}

#square {
  height: 100px;
  width: 100px;
  background-color: black;
  position: relative;
  left: 200px;
  top: -100px;
  opacity: 0;
  /* 将过渡属性放到基础样式中,确保显示/隐藏都生效 */
  transition: opacity 1s;
}

#shapes {
  height: 100px;
  width: 100px;
}

#shapes:hover>#square {
  opacity: 1;
}

对应的HTML代码保持不变:

<div id="shapes">
  <div id="circle"></div>
  <div id="square"></div>
</div>

修改后,当鼠标移出shapes容器时,square元素的opacity会从1平滑过渡到0,实现和显示时一致的流畅动画。

内容的提问来源于stack exchange,提问作者Павел Федоровский

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:24:19