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

实现悬停下划线动画:延迟默认下划线至悬停动画结束

链接悬停下划线动画问题解决

需求与问题

需要实现的链接交互效果:

  • 悬停时:文字变为红色,原黑色下划线消失,红色下划线从左到右绘制
  • 鼠标离开时:红色下划线先完全收缩消失,再显示原黑色下划线(无动画)

当前实现的问题:鼠标离开时,黑色下划线会在红色下划线完全收缩前提前出现,导致视觉冲突。

原代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:24:53