实现方块从顶部中心到底部中心的边框动画,修复现有代码跳变问题
你现有代码的跳变问题来自borderColors动画用了steps(1)阶跃过渡,加上伪元素的尺寸、定位属性切换没有做连贯衔接,而且伪元素z-index: -1会被下层背景图遮挡。我调整了实现逻辑,用CSS渐变模拟边框,全程平滑动画,内部完全透明可以透出下层背景,符合你的需求:
修改后的完整代码
CSS部分
.section-hero { position: relative; } .section-hero .image-background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; } .section-hero .image-background img { width: 100%; height: 100%; object-fit: cover; } .section-hero .section-container-content { padding: 20px; } .section-hero .hero-wrapper { display: flex; flex-direction: column; flex-wrap: wrap; align-items: center; justify-content: center; min-height: 500px; } .section-hero .section-wrapper { padding: 0 20px; } /* 边框动画核心样式 */ .section-hero .section-wrapper.animated-border { --border-width: 1px; --animation-speed: 3s; --color: #dda72e; position: relative; /* 四个渐变分别对应上下左右四条边框 */ background: linear-gradient(var(--color), var(--color)) top left, linear-gradient(var(--color), var(--color)) top right, linear-gradient(var(--color), var(--color)) bottom left, linear-gradient(var(--color), var(--color)) bottom right; background-size: 0% var(--border-width), /* 上边框初始宽度为0,位于顶部中间 */ var(--border-width) 0%, /* 右边框初始高度为0 */ 0% var(--border-width), /* 下边框初始宽度为0 */ var(--border-width) 0%; /* 左边框初始高度为0 */ background-repeat: no-repeat; animation: borderDraw var(--animation-speed) forwards ease-in-out; } @keyframes borderDraw { /* 第一阶段:上边框从中间向左右完全展开 */ 25% { background-size: 100% var(--border-width), var(--border-width) 0%, 0% var(--border-width), var(--border-width) 0%; } /* 第二阶段:左右两条边框同时从顶部向下延伸到底部 */ 50% { background-size: 100% var(--border-width), var(--border-width) 100%, 0% var(--border-width), var(--border-width) 100%; } /* 第三阶段:下边框从左右两端向中间汇合,完全铺满 */ 100% { background-size: 100% var(--border-width), var(--border-width) 100%, 100% var(--border-width), var(--border-width) 100%; } }
HTML部分(和原代码一致,无需修改)
<section class="section-hero"> <div class="container"> <div class="section-container-content"> <div class="image-background"> <img class="image-cover" src="https://via.placeholder.com/600x300"> </div> <div class="section-wrapper animated-border"> <div class="hero-wrapper"> <div class="section-intro"> <h1 class="section-title">title</h1> </div> </div> </div> </div> </div> </section>
说明
- 没有额外DOM元素、没有添加遮挡内部的背景层,容器内部全程透明,可正常透出下层背景图
- 动画路径完全符合要求:从顶部中心出发,先向左右铺满上边框,再沿左右两侧向下延伸,最后在底部中心汇合铺满下边框
- 可直接修改
animated-border类下的三个CSS变量调整边框宽度、动画速度、边框颜色,不需要修改动画逻辑
内容的提问来源于stack exchange,提问作者Vishal Bhatt
相关产品推荐
相关产品推荐

