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

如何实现图片悬停滑入Overlay效果且鼠标离开无反向过渡?

解决图片悬停Overlay滑入、离开时直接隐藏的问题

我明白你的需求:想要鼠标悬停时Overlay从底部平滑滑入,但鼠标离开时直接隐藏,不要反向的过渡动画。原代码里的CSS过渡是绑定在.overlay上的,所以不管是hover触发的height增加还是离开时的height减少,都会执行过渡效果,这就是问题所在。下面用JavaScript结合CSS调整来实现你要的效果:

修改后的完整代码

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
  position: relative;
  width: 50%;
}

.image {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 0;
  /* 初始不设置过渡,由JS动态添加 */
}

.overlay.slide-in {
  transition: .5s ease; /* 只在滑入时应用过渡 */
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}
</style>
</head>
<body>

<h2>Slide in Overlay from the Bottom</h2>
<p>Hover over the image to see the effect.</p>

<div class="container">
  <img src="img_avatar.png" alt="Avatar" class="image">
  <div class="overlay">
    <div class="text">Hello World</div>
  </div>
</div>

<script>
const container = document.querySelector('.container');
const overlay = container.querySelector('.overlay');

container.addEventListener('mouseenter', () => {
  // 滑入时添加过渡类,再设置高度为100%
  overlay.classList.add('slide-in');
  overlay.style.height = '100%';
});

container.addEventListener('mouseleave', () => {
  // 离开时先移除过渡类,直接设置高度为0
  overlay.classList.remove('slide-in');
  overlay.style.height = '0';
  
  // 可选:确保下次hover依然有动画,短时间后重新添加过渡类
  setTimeout(() => {
    overlay.classList.add('slide-in');
  }, 10);
});
</script>

</body>
</html>

代码解释

  1. CSS调整:把过渡效果从.overlay移到单独的.slide-in类中,这样只有我们主动添加这个类时,才会触发过渡动画。
  2. JavaScript逻辑:
    • mouseenter事件:给overlay加上slide-in类(启用过渡),然后设置height为100%,实现平滑滑入效果。
    • mouseleave事件:先移除slide-in类(禁用过渡),直接把height设为0,这样就不会有反向动画,瞬间隐藏Overlay。
    • 最后的setTimeout是为了确保下次鼠标悬停时,过渡类已经恢复,依然能看到滑入动画(如果不需要的话可以删掉这部分)。

这样修改后,就能完美实现你要的效果:悬停时平滑滑入,离开时直接隐藏~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:41:45