实现思路: 设置两个圆,用overflow:hidden各隐藏一半,使用绝对定位让一个位于左边半圆,一个位于右边半圆。然后使用transform:rotate 来旋转使得半圆动起来。
使用js函数传入两个参数,一个启始百分比和一个结束百分比,来控制进度的开始和停止。
HTML代码
<body>
<div class="contain">
<div class="left">
<div class="left-circle"></div>
</div>
<div class="right">
<div class="right-circle"></div>
</div>
<div class="mask">
<div class="number"></div>
</div>
</div>
</body>
CSS样式
<style>
.contain {
width: 200px;
height: 200px;
margin: 200px auto;
/* background-color: pink; */
position: relative;
}
.left {
position: absolute;
top: 0;
left: 0;
width: 50%;
height: 100%;
overflow: hidden;
}
.left-circle {
position: absolute;
left: 0;
width: 200%;
height: 100%;
border: 10px solid orange;
border-radius: 50%;
box-sizing: border-box;
border-top-color: transparent;
border-left-color: transparent;
transform: rotate(-45deg);
box-sizing: border-box;
/* animation: circleRotate 2s linear forwards 2s; */
}
.right {
position: absolute;
top: 0;
right: 0;
width: 50%;
height: 100%;
overflow: hidden;
/* background-color: rgb(22, 133, 70); */
}
.right-circle {
position: absolute;
right: 0;
width: 200%;
height: 100%;
border: 10px solid orange;
border-radius: 50%;
box-sizing: border-box;
border-bottom-color: transparent;
border-right-color: transparent;
transform: rotate(-45deg);
/* animation: circleRotate 2s linear forwards; */
}
/* @keyframes circleRotate {
from {
transform: rotate(-45deg);
}
to {
transform: rotate(105deg);
}
} */
.mask {
width: 30%;
height: 40%;
color: #fff;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
left: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.number {
color: red;
font-size: 30px;
}
</style>
JS代码:
function go (start, end) {
const circleLeft = document.querySelector('.left-circle')
const circleRight = document.querySelector('.right-circle')
const number = document.querySelector('.number')
function formatDegreeLeft (percent) {
// 封装左边圆角度
return `rotate(${-225 + (360 / 100 * percent)}deg)` // 旋转角度要与定时器相对应,我这使用的是6s转动360度
}
function formatDegreeRight (percent) {
// 封装右边圆角度
return `rotate(${-45 + (360 / 100 * percent)}deg)`
}
function setRotateLeft (node, percent) {
// 设置旋转左圆的角度
node.style.transform = formatDegreeLeft(percent)
}
function setRotateRight (node, percent) {
// 设置旋转右圆的角度
node.style.transform = formatDegreeRight(percent)
}
let percent = start //百分比
let t = setInterval(() => {
percent++
if (percent >= 0 && percent <= 50) { //如果百分比在50以内旋转右边圆
setRotateRight(circleRight, percent)
} else if (percent > 50 && percent <= 100) { //如果百分比在50以上,固定右半边圆和旋转左半边圆
circleRight.style.transform = 'rotate(135deg)'
setRotateLeft(circleLeft, percent)
}
number.textContent = percent + '%'
if (percent >= end) {
clearInterval(t)
if(percent>=100){
number.textContent = '加载完成'
}
}
}, 60)
}
go(60, 90) // 进度60 到进度90