如何将Div的虚线边框制作为可重复的进度条动画?
动态填充虚线边框的实现方案
方法一:多层背景渐变模拟填充动画
这种方法无需额外元素,直接通过背景层模拟新颜色边框,配合动画改变背景尺寸,适配宽度不固定的场景。
/* 基础样式 */ .box { position: relative; padding: 1rem; /* 原虚线边框 */ border: 2px dashed #cccccc; /* 四层背景对应上、下、左、右四边 */ background: linear-gradient(to right, #2196f3 0%, #2196f3 100%) top / 0% 2px no-repeat, linear-gradient(to right, #2196f3 0%, #2196f3 100%) bottom / 0% 2px no-repeat, linear-gradient(to bottom, #2196f3 0%, #2196f3 100%) left / 2px 0% no-repeat, linear-gradient(to bottom, #2196f3 0%, #2196f3 100%) right / 2px 0% no-repeat; /* 动画配置:3秒线性过渡,无限重复 */ animation: fill-border 3s linear infinite; } /* 关键帧动画:逐步扩展各边背景尺寸 */ @keyframes fill-border { 0% { background-size: 0% 2px, 0% 2px, 2px 0%, 2px 0%; } 25% { background-size: 100% 2px, 0% 2px, 2px 100%, 2px 0%; } 50% { background-size: 100% 2px, 100% 2px, 2px 100%, 2px 0%; } 75% { background-size: 100% 2px, 100% 2px, 2px 100%, 2px 100%; } 100% { background-size: 0% 2px, 0% 2px, 2px 0%, 2px 0%; } }
原理:用四层独立线性渐变分别模拟四个方向的边框,通过background-size控制显示范围,在关键帧中逐步将各边背景尺寸扩展至100%,实现边框逐步填充的效果。
方法二:伪元素 + Clip-path 动画
通过伪元素生成新颜色虚线边框,利用clip-path裁剪显示区域,配合动画扩大显示范围模拟填充。
/* 基础样式 */ .box { position: relative; padding: 1rem; /* 原虚线边框 */ border: 2px dashed #cccccc; } /* 伪元素:生成新颜色虚线边框 */ .box::before { content: ''; position: absolute; /* 与原边框对齐:偏移量等于原边框宽度 */ top: -2px; left: -2px; right: -2px; bottom: -2px; border: 2px dashed #2196f3; /* 初始裁剪:完全隐藏伪元素 */ clip-path: inset(100% 100% 0 0); animation: fill-border-clip 3s linear infinite; } /* 关键帧动画:逐步扩大裁剪区域 */ @keyframes fill-border-clip { 0% { clip-path: inset(100% 100% 0 0); } 25% { clip-path: inset(0 100% 100% 0); } 50% { clip-path: inset(0 0 100% 0); } 75% { clip-path: inset(0 0 0 0); } 100% { clip-path: inset(100% 100% 0 0); } }
原理:伪元素覆盖原div边框区域,初始通过clip-path完全隐藏,动画中逐步调整inset参数扩大显示范围,直到完整显示新颜色边框,最后重置状态重复动画。
注意事项
- 两种方法均支持宽度不固定场景,通过百分比或相对定位自适应尺寸变化。
- 可调整动画时长、关键帧节点、颜色值适配需求。
- 如需更平滑过渡,可增加关键帧节点优化节奏。
内容的提问来源于stack exchange,提问作者user2989367
相关产品推荐
相关产品推荐

