要制作带有进度条的计数器效果,可以使用CSS的伪元素和动画特性。
首先,需要在HTML中创建一个包含计数器数字和进度条的容器元素,比如一个div元素。然后,可以使用CSS的伪元素:before
来创建进度条,将其定位在容器元素的顶部,并设置宽度为0,高度和背景颜色可以自行选择。
接下来,可以使用CSS的动画特性@keyframes
和animation
来控制进度条的宽度,实现逐渐增长的效果。关键词包括@keyframes
、animation
、width
、position
、background-color
、transform-origin
等。
以下是一个制作带有进度条的计数器效果的示例代码:
<div class="counter">
<span class="count">0</span>
</div>
.counter {
position: relative;
width: 100px;
height: 20px;
background-color: #eee;
}
.counter:before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #4CAF50;
animation: progress 5s linear;
transform-origin: left;
}
@keyframes progress {
from {
width: 0;
}
to {
width: 100%;
}
}
.count {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-align: center;
line-height: 20px;
font-size: 16px;
font-weight: bold;
}
在上面的示例中,通过给容器元素.counter
设置position: relative
,可以让进度条伪元素.counter:before
相对于容器元素定位。同时,为了让进度条宽度逐渐增长,animation
属性设置了progress
关键帧规则,并设定了持续时间为5秒,线性动画方式,即animation: progress 5s linear
。
最后,为了让计数器数字始终居中显示,使用绝对定位和text-align: center
、line-height
属性来实现。