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

如何实现<a>标签鼠标悬停时的下划线动画效果?

问题分析与修复方案

你的代码存在几个关键问题,导致下划线动画无法正常工作,以下是具体修复点和完整代码:

核心问题说明

  • 父元素未设置相对定位:绝对定位的::after伪元素需要以<a>标签为定位基准,否则会相对于整个文档流偏移,无法对齐文本。
  • transform方向颠倒:原示例的“滑入”效果需要伪元素初始状态向下偏移,hover时回归原位,你的代码逻辑刚好相反。
  • 行内元素宽度无效:<a>默认是行内元素,设置width: 95%不会生效,需改为inline-block或block。
  • 背景色继承错误:background-color: inherit会继承父元素背景色,而非链接文本颜色,应使用currentColor确保下划线与文本颜色一致。

修复后的完整CSS代码

#about-text-box a {
    text-decoration: none;
    font-size: 17pt;
    font-family: 'Silkscreen', cursive;
    color: #ECE0E7;
    text-align: center;
    width: 95%;
    display: inline-block; /* 让width属性生效 */
    text-shadow: 2px 2px 2px #101400;
    position: relative; /* 为伪元素提供定位基准 */
    transition: 0.5s;
}

#about-text-box a:hover::after, #about-text-box a:focus::after {
    opacity: 1;
    transform: translate3d(0, 0, 0); /* hover时下划线回归原位 */
}

#about-text-box a::after {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 0.1em;
    background-color: currentColor; /* 继承文本颜色 */
    opacity: 0;
    transform: translate3d(0, 0.2em, 0); /* 初始状态向下偏移 */
    transition: opacity 300ms, transform 300ms;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:25:20