Home  >  Article  >  Web Front-end  >  CSS3圆形百分比进度条的实现原理_html/css_WEB-ITnose

CSS3圆形百分比进度条的实现原理_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:42:251304browse

原文  http://ymblog.net/2015/06/20/css3圆形百分比进度条的实现原理/

 

今天早上起来在查看jquery插件机制的时候,一不小心点进了css3圆形百分比进度条的相关文章,于是一发不可收拾,开始折腾了。。。

关于圆形圈的实现,想必用2个圆心相同,半径不同的div即可实现。大圆的颜色即为圆形进度条的底色,小圆的颜色即为中间百分比的遮罩颜色白色, 还要加上左右2边一边一个半圆,也就是说总共应该有4个div,一个大圆的div中包含3个div,左右一边半个圆,遮罩div处于最上面。

那这里的一边半个圆怎么实现呢?使用css的clip属性即可切图一样的只显示一半,这里稍后详细介绍。

这种实现效果其实是可以的(当百分比不超过50%的时候),当超过以后,就会发现,比如是60%,但进度条显示的是40%,这是为什么呢?因为左 右旋转的div没有遮住的缘故,超过了各自所在的范围应该hidden才行,不然多余的部分同样会显示出来。如图所示,当40%的时候正常,当60%的时 候是一样的,

那我们是不是还需要额外的2个div,来起到遮盖的作用,来看html代码

<div class="circle"><div class="pie_left"><div class="left"></div></div><div class="pie_right"><div class="right"></div></div><div class="mask"><span>10</span>%</div></div>

样式:

.circle {width: 200px;height: 200px;position: absolute;border-radius: 50%;background: #0cc;}.left,.right{width:200px;height:200px;position: absolute;top: 0px;left: 0px;}.pie_left, .pie_right{width:200px;height:200px;position: absolute;border-radius: 50%;top: 0px;left: 0px;background: red;}.pie_right,.right {clip:rect(0,auto,auto,100px);}.pie_left , .left{clip:rect(0,100px,auto,0);}/**当top和left取值为auto时,相当于0*当bottom和right取值为auto时,相当于100%*/.mask {width: 150px;height: 150px;border-radius: 50%;left: 25px;top: 25px;/*background: #FFF;*/position: absolute;text-align: center;line-height: 150px;font-size: 16px;}

这里js代码就比较简单了,只需要稍微做一下判断:

$(function(){if( $('.mask span').text() <= 50 ){$('.pie_right').css('transform','rotate('+($('.mask span').text()*3.6)+'deg)');}else{$('.pie_right').css('transform','rotate(180deg)');$('.pie_left').css('transform','rotate('+(($('.mask span').text()-50)*3.6)+'deg)');}})

说明:因为100%对应的是360度,那么50%对应的就是180度,1/3.6度。

再来介绍Clip属性

clip我们常用的就是rect()了,详细介绍请看 这篇文章 ,clip的兼容性也还可以,在兼容基本浏览器。

clip用法

对于一个属性设置为position:absolute;或者position:fixed;的元素设置才有作用。

clip:rect(top,right,bottom,left);

在IE6`7中,把属性之间的逗号去掉即可。

这里的right和bottom值都是相对于left和top的,包含在选中区域内的像素,就会显示出来,其它的都会隐藏。

那要是万一,bottom小于top,right小于left呢?那就整张图片就隐藏了。

还有需要注意的是,

  • 当left和top取值为auto时,它们的值为0px,
  • 当right和bottom取值为bottom时,他们默认的值为100%;
  • 这里要认真的理解一下,结合right和bottom值是相对于left和top的。这样应该会好理解一些。

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn