鼠标移开时hover:after过渡效果失效,如何实现移出时的淡出过渡?
问题原因
你当前的代码仅在 hover 状态下给伪元素设置了width:100%和left:0,默认状态下这两个属性未定义。鼠标移出时,伪元素的宽度会瞬间变回0(空内容的行内元素默认宽度为0),导致元素直接消失,根本来不及展示 opacity 的淡出过渡效果。
两种解决方案
方案一:保留宽度展开动画 + 淡出效果
把width、left也加入过渡属性,并在默认状态下设置初始值,让 hover 和移出时的所有变化都参与过渡:
.underline-hover-effect { position: relative; /* 必须添加,确保伪元素相对当前元素定位 */ } .underline-hover-effect:after { content: ""; position: absolute; height: 2px; opacity: 0; bottom: -5px; left: 50%; /* 初始位置居中 */ width: 0; /* 初始宽度为0 */ background-color: #6415ff; transition: opacity 300ms ease, width 300ms ease, left 300ms ease; } .underline-hover-effect:hover::after { width: 100%; left: 0; opacity: 1; }
方案二:仅保留透明度淡入淡出
如果不需要宽度展开的动画,直接让伪元素默认占满整个宽度,只通过透明度控制显示隐藏:
.underline-hover-effect { position: relative; /* 必须添加,确保伪元素相对当前元素定位 */ } .underline-hover-effect:after { content: ""; position: absolute; height: 2px; opacity: 0; bottom: -5px; left: 0; width: 100%; /* 默认占满父元素宽度 */ background-color: #6415ff; transition: opacity 300ms ease; } .underline-hover-effect:hover::after { opacity: 1; }
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

