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

如何实现页面加载时触发CSS ::after底部边框动画而非hover触发

实现页面加载自动执行的底部边框动画(无需JavaScript)

直接用CSS动画就能搞定,不用写JS。核心是把原来依赖hover触发的transition换成@keyframes动画,同时设置动画结束后保留最终状态:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
       
<style>
    .border-bottom-animate:after {
        content: "";
        display: block;
        width: 0%;
        border-bottom: 5px dotted black;
        /* 用animation替代hover触发的transition */
        animation: borderExpand .5s forwards;
    }
    
    /* 定义动画:从宽度0%过渡到100% */
    @keyframes borderExpand {
        to {
            width: 100%;
        }
    }
</style>
    </head>
<body>
    <div class="container border-bottom-animate">
        <p style="font-size: xx-large">
            现在页面加载时会自动执行边框动画了
        </p>
        
    </div>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js" integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>

关键说明:

  • @keyframes borderExpand:定义了边框从0宽度扩展到100%宽度的动画过程
  • animation: borderExpand .5s forwards:指定执行这个动画,时长0.5秒,forwards属性让动画结束后停在最后一帧(也就是宽度100%的状态),完美满足你要的"动画结束后边框保留"的要求
  • 完全去掉了原来的hover触发逻辑,页面一加载动画就自动执行一次

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:35:20