如何实现鼠标移出后背景图保留至transform动画结束再切换?
解决hover移出后背景图突然消失的问题
问题根源是你仅在hover状态下给.child添加背景图,鼠标移出后该属性被移除,导致背景图直接消失,无过渡效果。我们可以通过伪元素承载背景图的方式,配合过渡属性实现背景图随缩放动画平滑消失:
修改后的完整代码
CSS
html, body { margin: 0px; padding: 0px; } .wrapper { max-width: 1200px; text-align: center; margin-left: auto; margin-right: auto; } .container { width: 45%; margin: 20px; height: 300px; border: 3px solid #eee; overflow: hidden; position: relative; display: inline-block; cursor: pointer; } .child { height: 100%; width: 100%; background-color: darkgray; position: relative; transition: transform .5s ease; } /* 用伪元素承载背景图,默认隐藏 */ .child::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: url(https://images.freeimages.com/images/large-previews/de7/energy-1-1176465.jpg); background-size: cover; background-repeat: no-repeat; opacity: 0; transition: all .5s ease; transform: scale(1); } /* 遮罩层改用伪元素实现过渡 */ .child::after { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(52, 73, 94, 0.75); opacity: 0; transition: opacity .5s ease; z-index: 1; } span { display: block; font-size: 35px; color: #ffffff !important; font-family: sans-serif; text-align: center; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; height: 50px; cursor: pointer; text-decoration: none; z-index: 2; /* 确保文字在最上层 */ } .container:hover .child, .container:focus .child { transform: scale(1.2); } .container:hover .child::before, .container:focus .child::before { opacity: 1; transform: scale(1.2); /* 和父元素同步缩放 */ } .container:hover .child::after, .container:focus .child::after { opacity: 1; }
HTML
<div class="wrapper"> <div class="container"> <div class="child"> <span>Text</span> </div> </div> </div>
核心修改说明
- 把背景图移到
.child::before伪元素中,默认通过opacity:0隐藏,避免hover移出时属性丢失导致突然消失 - 给伪元素添加过渡属性,让透明度、缩放效果都能平滑触发
- 遮罩层改用
.child::after伪元素,通过opacity控制显示/隐藏,保持过渡一致性 - 设置文字的
z-index:2,确保它在背景图和遮罩层上方,不被遮挡
调整后,鼠标hover时背景图淡入并同步缩放,移出时背景图会随缩放动画一起淡出,和文字的视觉效果保持统一。
内容的提问来源于stack exchange,提问作者AnotherRandomUser
相关产品推荐
相关产品推荐

