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

CSS Transition Property问题:图片hover移出时无过渡效果求助

解决CSS Transition移出hover时图片无过渡效果的问题

问题现象

鼠标hover在<main>标签上时,图片按设置的位置过渡显示,但鼠标移出后图片瞬间消失,未应用过渡效果;仅使用背景色时该功能正常。

原始代码

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

main {
  width: 900px;
  height: 600px;
  margin: 10px auto;
  border: 1px solid black;
  position: relative;
  overflow: hidden;
}

.box {
  width: 300px;
  height: 600px;
  position: absolute;
  top: 0;
  left: -300px;
  transition: ease-out;
  transition: 2s;
}

main:hover .box:nth-child(1) {
  top: 0;
  left: 0;
  background: url('https://picsum.photos/seed/picsum/300/600');
  background-size: cover;
}

main:hover .box:nth-child(2) {
  top: 0;
  left: 300px;
  background: url('https://picsum.photos/id/237/300/600');
  background-size: cover;
}

main:hover .box:nth-child(3) {
  top: 0;
  left: 600px;
  background: url('https://picsum.photos/300/600.jpg');
  background-size: cover;
}

HTML

<main>
  <div class="box">

  </div>
  <div class="box">

  </div>
  <div class="box">

  </div>
</main>

问题原因

  1. 背景图仅在hover状态下添加:初始状态的.box没有背景图片属性,鼠标移出时元素直接从“有背景图”切换到“无背景图”,浏览器无法对这种状态变化应用过渡效果。
  2. transition属性写法错误:重复声明transition会导致前一个被覆盖,且未明确指定要过渡的属性,无法精准控制过渡效果。

解决方案

将背景图片设置在.box的初始状态中,hover状态仅修改位置属性;同时修正transition属性的写法,确保过渡效果作用在位置变化上。

修改后的代码

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

main {
  width: 900px;
  height: 600px;
  margin: 10px auto;
  border: 1px solid black;
  position: relative;
  overflow: hidden;
}

.box {
  width: 300px;
  height: 600px;
  position: absolute;
  top: 0;
  left: -300px;
  /* 合并transition属性,指定对left属性应用2s的ease-out过渡 */
  transition: left 2s ease-out;
  background-size: cover;
}

/* 为每个.box设置初始背景图 */
.box:nth-child(1) {
  background: url('https://picsum.photos/seed/picsum/300/600');
}

.box:nth-child(2) {
  background: url('https://picsum.photos/id/237/300/600');
}

.box:nth-child(3) {
  background: url('https://picsum.photos/300/600.jpg');
}

/* hover状态仅修改位置属性 */
main:hover .box:nth-child(1) {
  left: 0;
}

main:hover .box:nth-child(2) {
  left: 300px;
}

main:hover .box:nth-child(3) {
  left: 600px;
}

HTML

<main>
  <div class="box">

  </div>
  <div class="box">

  </div>
  <div class="box">

  </div>
</main>

说明

  • 背景图提前加载在初始状态,保证鼠标移出时元素仅发生位置变化,背景图始终存在,过渡效果可正常触发。
  • transition: left 2s ease-out明确指定过渡作用的属性为left,避免属性覆盖问题,同时定义了过渡时长和缓动效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:40:28