2014-07-16 46 views
2

如何將藍線(atm 100%)的長度調整爲70%?使用jQuery處理SVG路徑長度

小提琴 http://jsfiddle.net/7FP3J/2/

HTML

<div id="p0">0%</div> 
<div id="p100">100%</div> 
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
    <path fill="none" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" stroke="#0074c4" d="M80,80 A80,80 0 1,180.61117636732928,100.45116865416591" stroke-width="3" id="test"/> 
</svg> 

CSS

#p0 { 
    color: #0074c4; 
    left: 60px; 
    position: absolute; 
    top: 72px; 
} 
#p100 { 
    color: #0074c4; 
    left: 240px; 
    position: absolute; 
    top: 144px; 
} 

JS

setCircleTo(70); 

function setCircleTo(percent) 
{ 
    // percent 
    // $('#test').attr('d','') 
} 

回答

6

最簡單的方法是使用短陣數組技巧。

function setCircleTo(percent) 
{ 
    var path = $('#test').get(0); 
    var pathLen = path.getTotalLength(); 
    var adjustedLen = percent * pathLen/100; 
    path.setAttribute('stroke-dasharray', adjustedLen+' '+pathLen); 
} 

Fiddle here

+0

感謝FPR這很好的解決方案,但是,從左側的小線應爲藍色(全部時間):/ http://jsfiddle.net/7FP3J/21/ – Peter

+1

你的意思喜歡這個? http://jsfiddle.net/7FP3J/23/如果沒有,那麼你可能需要更好地描述你想要的內容來編輯你的問題,因爲我沒有遵循。 –