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的。這樣應該會好理解一些。