CSS滑动条动画问题:实现带拐角平滑过渡的边框环绕匀速动画
红色线条环绕内容盒并拐角平滑弯曲的实现方案
你的问题出在关键帧同时修改宽高和位置,导致线条未到拐角就变形,且没有处理拐角的平滑过渡。以下是满足需求的实现方式:
完整代码
<div id="main"> Contents </div>
#main { min-height: 300px; position: relative; padding: 20px; border: 2px solid transparent; overflow: hidden; } #main::after { content: ''; position: absolute; top: 0; left: 0; width: 10%; height: 2px; background: red; border-radius: 1px; animation: border-loop 4s linear infinite; } @keyframes border-loop { /* 上边:从左向右移动,保持笔直 */ 0%, 20% { top: 0; left: 0; width: 10%; height: 2px; transform: translateX(0); border-radius: 1px; transform-origin: left center; } /* 右上角拐角:转为圆形,准备向下 */ 25% { top: 0; left: calc(100% - 10px); width: 10px; height: 10px; transform: rotate(0); border-radius: 50%; transform-origin: top right; } /* 右边:从上向下移动,保持笔直 */ 30%, 50% { top: 0; left: calc(100% - 2px); width: 2px; height: 10%; transform: translateY(0) rotate(90deg); border-radius: 1px; transform-origin: top center; } /* 右下角拐角:转为圆形,准备向左 */ 55% { top: calc(100% - 10px); left: calc(100% - 10px); width: 10px; height: 10px; transform: rotate(90deg); border-radius: 50%; transform-origin: bottom right; } /* 下边:从右向左移动,保持笔直 */ 60%, 80% { top: calc(100% - 2px); left: calc(100% - 10%); width: 10%; height: 2px; transform: translateX(0) rotate(180deg); border-radius: 1px; transform-origin: right center; } /* 左下角拐角:转为圆形,准备向上 */ 85% { top: calc(100% - 10px); left: 0; width: 10px; height: 10px; transform: rotate(180deg); border-radius: 50%; transform-origin: bottom left; } /* 左边:从下向上移动,回到起点 */ 90%, 100% { top: calc(100% - 10%); left: 0; width: 2px; height: 10%; transform: translateY(0) rotate(270deg); border-radius: 1px; transform-origin: bottom center; } }
关键要点
- 拆分动画阶段:将直边移动和拐角过渡分开,避免同时修改宽高和位置导致的变形
- 拐角用圆形模拟弯曲:在拐角节点将线条改为10px的圆形,配合旋转实现平滑转弯
- 控制旋转原点:通过
transform-origin确保线条在旋转时的中心点正确,保证运动轨迹贴合容器边缘 - 匀速运动:使用
linear动画曲线,让整个环绕过程速度一致
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

