CSS3实现圆形进度条

时间:2023-03-09 03:56:10
CSS3实现圆形进度条

介绍

  闲来无事,去了CSS3Plus网站逛了逛,发现了一个很有意思的实现--css3实现进度条。粗略看了下代码,发现原理其实很简单,不难理解。

现在在此讲述下原理并实现一个1s更新的进度条。

  技术细节是这样的:进度条由两个半圆环组成,首先我们的任务是实现左右两个半圆环。圆环可以用border-radius实现,这样就意味着该方

法不兼容IE8.可以使用clip来完成对整圆环的剪切;使用rotate函数完成圆环的旋转,通过设置两个半圆环的旋转角度来实现不同进度值的显示。

  clip属性是css2属性,所有的浏览器都支持该属性。对于clip有几个要点需要注意:首先,使用clip属性的元素必须是绝对定位或者固定定位的

元素,也就是说必须脱离文档流;其次,clip可以使用的函数目前只有rect(top,right,bottom,left),该函数传递4个值,其中top为裁剪区域距离

元素顶端的距离,设为auto时默认为0,right为裁剪区域距离元素左端(左边框)的值,auto时默认为元素的最右端,bottom为裁剪区域距离元

素顶端的值,auto时默认为元素最底端,left为距离元素左边的距离,auto时默认为0.

实现

  

        .wrap{position: relative;width: 200px;height:200px;border-radius: 50%;background: #CCFFFF;text-align: center;}
.right-part{width:200px;height: 200px;position: absolute;clip:rect(0px,auto,auto,100px)}
.right{width: 200px;height:200px;position: absolute;border-radius: 50%;background: #003366;
clip:rect(0px,auto,auto,100px);}
.r-shadow{width: 150px;height:150px;border-radius: 50%;background: #fff;position: absolute;
left:25px;top:25px;} .left-part{width:200px;height: 200px;position: absolute;clip:rect(0px,100px,auto,0px)}
.left{width: 200px;height:200px;position: absolute;border-radius: 50%;background: #003366;
clip:rect(0px,100px,auto,0px);}
.l-shadow{width: 150px;height:150px;border-radius: 50%;background: #fff;position: absolute;
left:25px;top:25px;}
#desc{display:inline-block;width:200px;height:200px;line-height: 200px;font-size: 56px;position: absolute;
left:;}
     <div class="wrap">
<div class="right-part">
<div class="right" id="right"></div>
<div class="r-shadow"></div>
</div>
<div class="left-part">
<div class="left" id="left"></div>
<div class="l-shadow"></div>
</div>
<span id="desc">ad</span>
</div>
      function progressBar(percentage){
var p = Math.round(percentage * 100);
var deg = p * 3.6;
var right = document.getElementById("right"),
left = document.getElementById("left"),
desc = document.getElementById("desc");
if(p > 100 || p < 0) p = 100;
if(deg <= 180){
right.style.cssText = "transform:rotate("+(deg-180)+"deg);"
left.style.cssText = "background:#CCFFFF;"
}else{
right.style.cssText = "transform:none;"
left.style.cssText = "background:#003366;transform:rotate("+(deg-360)+"deg);"
}
if(desc.innerText){
desc.innerText = p+"%"
}
if(desc.textContent){
desc.textContent = p+"%";
}
}
var g = 0;
setTimeout(function _a(){
if(g>1)return;
progressBar(g);
g += 0.1
setTimeout(_a,1000)
},1000)