如何将链接hover下划线效果改为无需悬停自动循环播放的持续效果
最终修改后可直接运行的代码
CSS部分
.efeitosublinhado{ position: relative; text-decoration: none; } .efeitosublinhado::before{ content: ''; position: absolute; bottom: 0; left: 0; width: 0; height: 2px; background-color: red; /* 直接绑定无限循环动画,加载即触发 */ animation: linky 2s infinite ease-in-out; -moz-animation: linky 2s infinite ease-in-out; -webkit-animation: linky 2s infinite ease-in-out; } @keyframes linky{ 0%{ width: 0%; } 50%{ width: 100%; } 100%{ width: 0%; } } @-moz-keyframes linky{ 0%{ width: 0%; } 50%{ width: 100%; } 100%{ width: 0%; } } @-webkit-keyframes linky{ 0%{ width: 0%; } 50%{ width: 100%; } 100%{ width: 0%; } } /* 可选:如果需要保留hover时固定下划线的效果,新增以下规则即可 */ .efeitosublinhado:hover::before{ animation-play-state: paused; width: 100%; }
HTML部分
<a href="WWW.google.pt" class="efeitosublinhado"> this text will border bottom effect </a>
核心改动说明
- 移除了冗余的
.efeitosublinhado2类和原有的hover触发逻辑,直接把无限循环动画绑定到链接的::before伪元素上,页面加载后就会自动播放,不需要hover触发 - 调整了
@keyframes的帧规则,新增50%位置的宽度100%状态,让下划线可以完成「从左到右展开→从右到左收起」的平滑循环,避免到100%后直接跳回0的生硬效果 - 修正了HTML标签里的类名错误,和CSS定义的类名保持一致
内容的提问来源于stack exchange,提问作者José Oliveira
相关产品推荐
相关产品推荐

