实现悬停下划线动画:延迟默认下划线至悬停动画结束
链接悬停下划线动画问题解决
需求与问题
需要实现的链接交互效果:
- 悬停时:文字变为红色,原黑色下划线消失,红色下划线从左到右绘制
- 鼠标离开时:红色下划线先完全收缩消失,再显示原黑色下划线(无动画)
当前实现的问题:鼠标离开时,黑色下划线会在红色下划线完全收缩前提前出现,导致视觉冲突。
原代码
a { position: relative; text-decoration: underline; color: black; transition: color 0.3s; } a::before { content: ''; position: absolute; width: 0; height: 1px; bottom: 0; left: 0; background-color: red; transition: width 0.3s; } a:hover { text-decoration: none; color: red; } a:hover::before { width: 100%; }
<a href="google.com">My link to Google</a>
解决方案
通过给text-decoration添加过渡延迟,让原黑色下划线的显示时机滞后于红色下划线的收缩动画,修改后的代码如下:
a { position: relative; text-decoration: underline; color: black; /* 延迟text-decoration的显示,等待红色下划线收缩完成 */ transition: color 0.3s, text-decoration 0s 0.3s; } a::before { content: ''; position: absolute; width: 0; height: 1px; bottom: 0; left: 0; background-color: red; transition: width 0.3s; } a:hover { text-decoration: none; color: red; /* 悬停时取消延迟,让原下划线立即消失 */ transition: color 0.3s, text-decoration 0s; } a:hover::before { width: 100%; }
原理说明
- 默认状态下,
text-decoration的过渡设置为0s 0.3s:表示下划线的显示/隐藏没有过渡动画,但会延迟0.3秒执行,刚好匹配红色下划线的收缩时长,确保红色线完全消失后再显示原黑色下划线。 - 悬停状态下,重新定义
transition取消text-decoration的延迟:让鼠标悬停时原下划线立即消失,配合红色下划线的展开动画,保证悬停效果流畅。
内容的提问来源于stack exchange,提问作者Malvinka
相关产品推荐
相关产品推荐

