通过 纯 css来实现 模拟电池图标正在充电动态的效果,效果极佳,很真实还流畅。
下面是完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="battery"></div>
<style>
.battery {
width: 80px;
height: 40px;
color: green;
border: 2px solid currentColor;
border-right-color: transparent;
padding: 3px;
background:
repeating-linear-gradient(90deg, currentColor 0 10px, #fff 0 15px) 0/0% no-repeat content-box content-box;
position: relative;
box-sizing: border-box;
animation: focusing 2s infinite steps(6);
}
.battery::before {
content: "";
position: absolute;
top: -2px;
bottom: -2px;
left: 100%;
width: 10px;
background:
linear-gradient(#fff0 calc(50% - 7px), currentColor 0 calc(50% - 5px),
#fff0 0 calc(50% + 5px), currentColor 0 calc(50% + 7px), #fff0 0) left /100% 100%,
linear-gradient(currentColor calc(50% - 5px), #fff0 0 calc(50% + 5px), currentColor 0) left /2px 100%,
linear-gradient(#fff0 calc(50% - 5px), currentColor 0 calc(50% + 5px), #fff0 0) right/2px 100%;
background-repeat: no-repeat;
}
@keyframes focusing {
100% {
background-size: 120%
}
}
</style>
</body>
</html>
效果图
电池外观样式:
.battery的宽高分别为80px和40px,呈现出电池的基本形状。color: green设置颜色为绿色。border和border-right-color: transparent为电池添加了边框,模拟不同阶段的充电状态。padding增加了一定的空白区域,使视觉效果更自然。background属性使用了repeating-linear-gradient和linear-gradient从绿色到白色,象征电量从无到有。创建了一种动态的视觉效果,模拟电池的充电过程。
电池充电前的细节:
.battery::before伪元素负责创建电池充电的视觉细节,通过多个linear-gradient实现电池的边缘渐变和充电指示器。background-repeat: no-repeat确保了动画的连续性。
动画关键帧(@keyframes) :
@keyframes focusing是一个名为focusing的动画,它控制了电池充电过程的动画效果。100%关键帧定义了动画的终点,即电池充电完成时的状态。background-size: 120%意味着背景的大小会超出原本的100%,从而模拟充电过程中的膨胀效果。
接下来,我们详细解析动画过程:
动画启动:animation: focusing 2s infinite steps(6);定义了动画名为focusing,持续时间为2秒,无限循环,每步间隔为动画总时间的1/6。这将使电池充电过程看起来更流畅,每2秒完成一个完整的充电周期。
充电过程:随着动画的进行,.battery的背景颜色会从绿色逐渐变为透明,同时边框颜色会从绿色变为黑色,模拟电池从空到满的过程。::before伪元素的背景渐变也随着动画变化,指示器部分从左到右移动,代表电量的增加。
动画细节:使用linear-gradient的多段组合,赋予了电池充电指示器动态的视觉效果,增强了真实感。背景的大小变化,通过background-size的调整,使动画更具动态性。
动画结束:当动画执行到100%时,电池模拟完成充电,背景大小恢复到原始大小,完成了充电循环。