2013-12-13 139 views
1

我需要一點幫助。 在下面的代碼中,我想通過onmouse-event來控制星的旋轉。通過Javascript停止/啓動SVG旋轉

如果將鼠標移動到星形上,它應該旋轉。

我想到了在attributeName改變transform不同的東西,當鼠標不超過通過roationon()/off()功能的明星,這樣的旋轉不工作,但我不知道該怎麼做。

我很感激我能得到的每一個幫助。

感謝

<!DOCTYPE html> 
<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<html> 

<body> 

<script> 
function rotationon() {} 
function rotationoff() {} 
</script> 

<svg height="2000" width="2000"> 
<polygon id="stern1" points="100,10 40,180 190,60 10,60 160,180" fill="yellow" transform="translate(100, 100)" onmouseover="rotationon()" onmouseout="rotationoff()" > 
<animateTransform 
     attributeName="transform" 
     begin="0s" 
     dur="5s" 
     type="rotate" 
     from="0 100 100" 
     to="360 100 100" 
     repeatCount="indefinite" 
    /> 
    </polygon> 
</svg> 


</body> 
</html> 
+2

只是出於興趣,如果多數民衆贊成在所有你想要做的,你可以做到這一點沒有JavaScript,像http://jsfiddle.net/xaM6q/,但我懷疑你想要一個更好的解決方案來定製其他位。 – Ian

回答

1

有幾種不同的方式來處理這一點,這取決於它要與整合,以及它如何會與其他瀏覽器玩。我的直覺就是最終說出它的價值,就像使用Raphael,snap.svg,Pablo.js等其中的一個SVG庫,它們將幫助解決一些可能面臨的問題。

您也可以只使用純SVG就像我提到的http://jsfiddle.net/xaM6q/

但是,要使用你正在嘗試的方法,你可能想使用類似beginElement()和endElement,所以代碼可能看起來有點像以下...小提琴http://jsfiddle.net/xaM6q/2/

<script> 
    function rotationon(evt){ 
     document.getElementById('myanim').beginElement();  
    } 
    function rotationoff(){ 
     document.getElementById('myanim').endElement(); 
    } 
</script> 

<svg height="2000" width="2000"> 
    <g transform="translate(100,100)"> 
    <polygon id="stern1" points="100,10 40,180 190,60 10,60 160,180" fill="yellow" onmouseover="rotationon()" onmouseout="rotationoff()" > 
     <animateTransform 
     id="myanim" 
     attributeName="transform" 
     begin="indefinite" 
     dur="5s" 
     type="rotate" 
     from="0 100 100" 
     to="360 100 100" 
     fill="freeze" 
     repeatCount="indefinite" 
    /> 
    </polygon> 
    </g> 

幾件值得注意的事情。我已經添加了一個g元素來幫助保持轉換位置,因爲您可能需要這樣做(沒有它,您可能會發現它會移開)。此外,動畫可能有點不穩定,取決於你希望如何停止(我已經添加了'fill = freeze'),以及事件中動畫會發生什麼。

它值得了解所有這些以瞭解SVG動畫,但如前所述,我可能仍然會考慮使用第三方庫並手動控制旋轉,而不是使用animate標記,因此您可以暫停/輕鬆地以任意角度重新開始旋轉。