2016-05-30 44 views
0

這裏真的被卡住了,無法獲取SVG矩形計算的樣式

我已經創建了一個基於寬度爲%的矩形條。如果我調試它,我會看到計算菜單中的像素寬度。我曾嘗試在網上尋找解決方案,但沒有任何解決方案。

這是我創建的SVG矩形,它是條形圖的一部分。

<rect style="fill: white;" id="g2005" x="39px" y="240px" width="44.95%" height="15px" onmouseover="graphMouseIn(id)" onmouseout="graphMouseOut(id)"></rect> 

下面的代碼,我把XXXXX是我想要魔術插入像素計算寬度的地方。

<animate attributeName="width" from="0" to="XXXXX" dur="0.10s" fill="freeze"></animate> 

The width in pixel that i want to grab.

我曾試圖做一些事情來獲得它,但它進入未定義或空。

下面的代碼給我NULL

<animate attributeName="width" from="0" to=' + ($('#g' + sightingYear).width()) + ' dur="0.10s" fill="freeze" /> 

下面的代碼給我UNDEFINED

<animate attributeName="width" from="0" to=' + (('#g' + sightingYear).width) + ' dur="0.10s" fill="freeze" /> 

我一直在使用Window.getComputedStyle(),.InnerWidth,都沒有工作,也試過。請幫助我,我感謝您的幫助!提前致謝。 :)

+0

你不能叫'getComputedStyle'上SVGElements(其中jQuery的'.WIDTH()'不會調用),你需要'埃爾。 getBoundincClientRect()。width' – Kaiido

+0

@Kaiido'el.getBoundincClientRect()。width'將在'px'中提供寬度。 – ozil

+0

@ ozil,如果我正確地得到問題,那是OP所要的。 – Kaiido

回答

1

爲什麼你需要計算像素的寬度?你知道你可以使用百分比值嗎?

<animate attributeName="width" from="0%" to="44.95%"... 

演示

<svg width="500" viewBox="0 0 500 15"> 
 
    <rect width="44.95%" height="15px"> 
 
    <animate attributeName="width" from="0%" to="44.95%" dur="3.10s" fill="freeze"></animate> 
 
    </rect> 
 
</svg>

+0

謝謝,這工作正常,我想我在rect元素外有這個動畫元素。 –

+0

''不需要在''裏面,就像我在我的例子中所做的那樣。如果你願意,它可以在外面。 –