首页 > 解决方案 > 如何在悬停时为文本上的下划线设置动画并在鼠标上保持线条

问题描述

我看过很多关于如何为线条制作动画的问题和教程,但它们似乎并没有解决我的问题。我有一个带有下划线的文本,所以我希望用户将鼠标悬停在包含文本的 div 下方,并让该行从左到右进行动画处理,但之后保留该行。

这是我目前拥有的代码,但它非常有故障,边框底部和 :after 不能很好地协同工作,因为它们的高度不同

.cta-text{
    color: #2980FF;
    border-bottom: 3px solid #2980FF;
    transition: width .2s;
    
    &:hover{
        border-bottom: none;
    }

    &::after {
        content: '';
        width: 0;
        height: 3px;
        display: block;
        background: #2980FF;
    }

    &:hover::after {
        width: 100%;
        margin-top: -2px;
        transition: width .3s;
    }
}

这是一个代码笔示例https://codepen.io/godhandkiller/pen/jOrVjdq

标签: htmlcssanimationless

解决方案


使用@keyframes更改/暂停动画。

@keyframes hover {
 0% {
   // normal styles
 }
 100% {
   // hover styles
 }
}

.class {
 animation-name: hover;
 animation-duration: 1ms;
 animation-fill-mode: backwards;
 animation-play-state: paused;      
 }

.class:active,
.class:focus,
.class:hover {
   //hover style you define
 }

使用此链接查看示例。


推荐阅读